npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express_prisma_mongodb_server

v1.0.1

Published

Downloads

3

Readme

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: "[email protected]"}
  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 protected]`)
});
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 protected]
 */
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