How to use Prisma with express, postgress, and Graphql?

How to use Prisma with express, postgress, and Graphql?

·

4 min read

Welcome friends to this new blog. In this blog, you will learn how to set up APIs with the help of an express server. You will learn how to integrate graphql in the express server.

GitHub link — https://github.com/nextdev1111/prisma-postgres-graphql-express

Youtube Link -- https://youtu.be/AhNPzf8fHX4

📒Notes

  1. I will be using pnpm for this project but the tutorial will show you how to do it with npm.**

  2. We will be using typescript for this project.

Step1: 📦 Setup

Make a folder by whichever name you want but you need to consider npm naming restrictions.

Then run this command

npm init -y

Make another folder named src. Make a file named index.ts in the src folder.

[root folder]

--- src
--- --- index.ts

To install dependencies and setup typescript

This will install dependencies 👇

npm i @graphql-tools/schema @prisma/client dotenv express graphql express-graphql

This will install dev dependencies 👇

npm i -D @types/dotenv @types/express @types/node prisma ts-node typescript

This will download the below packages 👇

{
  "name": [YOUR-PROJECT-NAME-HERE],
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon src/index.ts",
    "build": "tsc -p ."
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@graphql-tools/schema": "^9.0.4",
    "@prisma/client": "^4.4.0",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "express-graphql": "^0.12.0",
    "graphql": "^16.6.0"
  },
  "devDependencies": {
    "@types/dotenv": "^8.2.0",
    "@types/express": "^4.17.14",
    "@types/node": "^18.8.3",
    "prisma": "^4.4.0",
    "ts-node": "^10.9.1",
    "typescript": "^4.8.4"
  }
}

Then type 👇 to create a tsconfig file.

npm install -g typescript
tsc --init

Step2: 🗃️ Prisma Setup with postgress database

Type this command in your terminal

npm prisma init

Prisma will set up two things in your root folder.

  1. Prisma folder

  2. .env file

In the prisma folder, you can find schema.prisma file.


// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Post {
  id        String   @id @default(cuid())
  text      String
  createdAt DateTime @default(now())
  user      User     @relation(fields: [userId], references: [id])
  userId    String
}

model User {
  id    String @id @default(uuid())
  name  String
  posts Post[]
}

Let’s add a database now.

go to https://railway.app/

Click on start new project

You can set up a PostgreSQL database. If you find any problem, you can also watch the youtube video.

Then, you should copy the postgresql database connection key

Then go to .env your project’s root folder.

Then change the connection string in your .env file.

→ Remember to also include the password in the connection string.

Then type

prisma db push

⚠️Errors

If you face any errors, you should check the connection string.

Step3: ✨Express Server

This is the basic express server

import express, { Request, Response } from "express";
import { PrismaClient } from "@prisma/client";

const app = express();
// instance of prisma client
const prisma = new PrismaClient();

// middlewares
app.use(express.json());


app.get("/", async (req: Request, res: Response) => {
  const posts = await prisma.post.findMany();

  return res.status(200).json({ success: true, posts });
});

app.post("/", async (req: Request, res: Response) => {
  const { text, userId } = req.body;

  const post = await prisma.post.create({
    data: {
      text,
      userId,
    },
  });

  return res.status(201).json({ success: true, post });
});

app.listen(3000, () => {
  console.log(`Listening to 3000`);
});

If you want to add an entry to your database. You can also use prisma studio

npm prisma studio

Step4: 💪Grahpql Integration

import express, { Request, Response } from "express";
import { PrismaClient } from "@prisma/client";

const app = express();
// instance of prisma client
const prisma = new PrismaClient();

// graphql
import { graphqlHTTP } from "express-graphql";
import { makeExecutableSchema } from "@graphql-tools/schema";

// graphql models
const graphqlModels = `
    type Post{
        id: ID
        text: String
        user: User
        userId: String
    }
    type User{
        id: ID
        name: String
        posts: [Post]
    }
    type Query{
      getPosts: [Post]  
      getUsers: [User]  
    }
`;

// Graphql Resolvers
const resolvers = {
  Query: {
    getPosts: () => {
      return prisma.post.findMany({
        include: {
          user: true,
        },
      });
    },
    getUsers: () => {
      return prisma.user.findMany({
        include: {
          posts: true,
        },
      });
    },
  },
};

// Graphql schema
const schema = makeExecutableSchema({
  resolvers,
  typeDefs: graphqlModels,
});

// using graphqlHTTP middleware
app.use(
  "/graphql",
  graphqlHTTP({
    schema: schema,
    graphiql: true,
  })
);

// middlewares
app.use(express.json());

app.get("/", async (req: Request, res: Response) => {
  const posts = await prisma.post.findMany();

  return res.status(200).json({ success: true, posts });
});

app.post("/", async (req: Request, res: Response) => {
  const { text, userId } = req.body;

  const post = await prisma.post.create({
    data: {
      text,
      userId,
    },
  });

  return res.status(201).json({ success: true, post });
});

app.listen(3000, () => {
  console.log(`Listening to 3000`);
});

You can use graphiql on this path

http://localhost:3000/graphql

If you want to ask any questions, feel free to ask 👇 Join the Next Dev Discord Server!

Did you find this article valuable?

Support Next Dev's Blog by becoming a sponsor. Any amount is appreciated!