DEV Community

Cover image for How to use Prisma with express, postgress, and Graphql?
Next Dev
Next Dev

Posted on • Edited on

4

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

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 Video in Hindi

📒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
Enter fullscreen mode Exit fullscreen mode

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

[root folder]

--- src
--- --- index.ts
Enter fullscreen mode Exit fullscreen mode

To install dependencies and setup typescript

This will install dependencies 👇

npm i @graphql-tools/schema @prisma/client dotenv express graphql express-graphql
Enter fullscreen mode Exit fullscreen mode

This will install dev dependencies 👇

npm i -D [@types/dotenv](http://twitter.com/types/dotenv) [@types/express](http://twitter.com/types/express) [@types/node](http://twitter.com/types/node) prisma ts-node typescript
Enter fullscreen mode Exit fullscreen mode
{
"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"
}
}
view raw package.json hosted with ❤ by GitHub

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
Enter fullscreen mode Exit fullscreen mode

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[]
}
view raw schema.prisma hosted with ❤ by GitHub



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
Enter fullscreen mode Exit fullscreen mode

⚠️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`);
});
view raw index.ts hosted with ❤ by GitHub



If you want to add an entry to your database.

You can also use prisma studio

npm prisma studio
Enter fullscreen mode Exit fullscreen mode

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`);
});
view raw index.ts hosted with ❤ by GitHub



You can use graphiql on this path

[http://localhost:3000/graphql](http://localhost:3000/graphql)
Enter fullscreen mode Exit fullscreen mode

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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay