1.0.1 • Published 2 years ago

express_prisma_mongodb_server v1.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

README.md

Express + Prisma + MongoDB | Speedrun

Mandatory Prerequisites:

  • Prisma+MongoDB+Express | Dual-Wielding High Octane Rage Fuel:
    • https://nodejs.org/en/download
    • https://www.mongodb.com/cloud/atlas/register
    • Go to Database Access => +ADD NEW DATABASE USER
    • Create a new cluster, free tier is fine.
    • Create a database within the cluster (View monitoring => Collections => +Create Database)
    • Choose Database name, and choose collection name.
    • Find The Database URL: mongodb+srv://:@cluster0.xxxxxxx.mongodb.net/
    • Go to Network Accesss => +Add IP Address => 0.0.0.0/0

Variables to Replace in the below script:

  • DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"
mkdir -p server/routes && cd server
npm init -y && npm pkg set type="module" scripts.dev="node index.js" scripts.demo="node ./prisma/demo_query.js"
npm install express cors morgan helmet @prisma/client
npm i --save-dev prisma

# npx prisma init # https://www.prisma.io/docs/getting-started/setup-prisma/start-from-scratch/mongodb-typescript-mongodb
mkdir prisma


cat <<'EOF' > .gitignore
**/.env
**/node_modules
**/package-lock.json
**/build
**/dist
**/tempCodeRunnerFile.*
**/.DS_Store
EOF


cat <<'EOF' > .env
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema

# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings

DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"
EOF


cat <<'EOF' > ./prisma/schema.prisma
// https://www.prisma.io/docs/concepts/components/prisma-schema
generator client {
  provider = "prisma-client-js"
}
datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}
model User {
  id    String @id @default(auto()) @map("_id") @db.ObjectId
  name  String
  email String
}
EOF


cat <<'EOF' > ./prisma/demo_query.js
/**
 * @run node query.js | deno run query.js
 */
async function main() {
  let PrismaClient;
  if (typeof Deno !== "undefined"    && "deno" in Deno.version)   PrismaClient = (await import("npm:@prisma/client")).PrismaClient
  if (typeof process !== "undefined" && process.title === 'node') PrismaClient = (await import("@prisma/client")).PrismaClient
  const prisma = new PrismaClient();

  let all_users = await prisma['user'].findMany(); console.log(all_users);
  if (all_users.length >= 1 ) return; 
  const bob = {name: "Bob", email: "bob@example.com"}
  console.log("No users found, creating example:", await prisma.user.create({data: bob }));
  await prisma.$disconnect().catch((e)=>console.log(e))
}; main()
EOF


npx prisma db push 
node ./prisma/demo_query.js


cat << 'EOF' > ./prisma/PrismaClient.js
/**
 * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-prismaclient/instantiate-prisma-client
 * @see https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#re-using-a-single-prismaclient-instance
 */
import { PrismaClient } from "@prisma/client";
const prisma = global.prisma || new PrismaClient();
if (process.env.NODE_ENV === "development") global.prisma = prisma;
export { prisma };
EOF










cat << 'EOF' > ./index.js
import express from "express"; import cors from "cors"; import morgan from "morgan"; import helmet from "helmet";
import users from "./routes/users.js"
const app = express();
app.use(express.json());
app.use(cors( /*{origin: "*"}*/));
app.use(helmet());
app.use(morgan("dev", { skip: () => process.env.NODE_ENV === "test" }));

app.get("/", (req, res) => { res.send("API Server Root!"); }); // Routing (API endpoints)
app.use("/api/users", users);

const port = process.env.PORT || 8000;
app.listen(port, async () => {
  (await import("child_process")).exec(`open http://localhost:${port}`, err => { if (err) throw err }); // preview server in browser
  console.log(`Try http://localhost:${port}/api/users    http://localhost:${port}/api/users/post?name=foo&email=bar@email.com`)
});
EOF


cat << 'EOF' > ./routes/users.js
import { prisma } from "../prisma/PrismaClient.js"
import express from "express"; const router = express.Router();

/**
 * @see https://expressjs.com/en/5x/api.html#router https://www.prisma.io/docs/concepts/components/prisma-client/crud
 * @run npm run dev
 * @see http://localhost:8000/api/users
 * @see http://localhost:8000/api/users/post?name=foo&email=bar@email.com
 */
router.get("/", async (req, res, next) => {
  let response = await prisma.user.findMany()
  res.status(200).send(JSON.stringify(response, null, 2))
  // next() // Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next() to continue matching subsequent routes. 
});
router.get("/post", async (req, res, next) => {
  let response = await prisma.user.create({ data: req.query }); response = {response, "query_params": req.query,}
  res.status(200).send(JSON.stringify(response, null, 2))
});
export default router;
EOF



node index.js
1.0.1

2 years ago

1.0.0

2 years ago