This example shows how to implement an GraphQL server (code-first) with TypeScript with the following stack:
- NestJS: Web framework for building scalable server-side applications
- Prisma Client: Databases access (ORM)
- Prisma Migrate: Database migrations
- SQLite: Local, file-based SQL database
The example was bootstrapped using the NestJS CLI command nest new nest-graphql
.
Download this example:
npx try-prisma@latest --template orm/nest-graphql
Then, navigate into the project directory:
cd nest-graphql
Alternative: Clone the entire repo
Clone this repository:
git clone git@github.com:prisma/prisma-examples.git --depth=1
Install npm dependencies:
cd prisma-examples/orm/nest-graphql
npm install
This example uses a local SQLite database by default. If you want to use to Prisma Postgres, follow these instructions (otherwise, skip to the next step):
-
Set up a new Prisma Postgres instance in the Prisma Data Platform Console and copy the database connection URL.
-
Update the
datasource
block to usepostgresql
as theprovider
and paste the database connection URL as the value forurl
:datasource db { provider = "postgresql" url = "prisma+postgres://accelerate.prisma-data.net/?api_key=ey...." }
Note: In production environments, we recommend that you set your connection URL via an environment variable, e.g. using a
.env
file. -
Install the Prisma Accelerate extension:
npm install @prisma/extension-accelerate
-
Add the Accelerate extension to the
PrismaClient
instance:+ import { withAccelerate } from "@prisma/extension-accelerate" + const prisma = new PrismaClient().$extends(withAccelerate())
That's it, your project is now configured to use Prisma Postgres!
Run the following command to create your database. This also creates the User
and Post
tables that are defined in prisma/schema.prisma
:
npx prisma migrate dev --name init
When npx prisma migrate dev
is executed against a newly created database, seeding is also triggered. The seed file in prisma/seed.ts
will be executed and your database will be populated with the sample data.
If you switched to Prisma Postgres in the previous step, you need to trigger seeding manually (because Prisma Postgres already created an empty database instance for you, so seeding isn't triggered):
npx prisma db seed
Launch your GraphQL server with this command:
npm run dev
Navigate to http://localhost:3000/graphql in your browser to explore the API of your GraphQL server in a GraphQL Playground.
The schema that specifies the API operations of your GraphQL server is defined in ./schema.graphql
. Below are a number of operations that you can send to the API using the GraphQL Playground.
Feel free to adjust any operation by adding or removing fields. The GraphQL Playground helps you with its auto-completion and query validation features.
query {
feed {
id
title
content
published
author {
id
name
email
}
}
}
See more API operations
{
draftsByUser(
userUniqueInput: {
email: "mahmoud@prisma.io"
}
) {
id
title
content
published
author {
id
name
email
}
}
}
mutation {
signupUser(data: { name: "Sarah", email: "sarah@prisma.io" }) {
id
}
}
mutation {
createDraft(
data: { title: "Join the Prisma Discord", content: "https://pris.ly/discord" }
authorEmail: "alice@prisma.io"
) {
id
viewCount
published
author {
id
name
}
}
}
mutation {
togglePublishPost(id: __POST_ID__) {
id
published
}
}
Note that you need to replace the __POST_ID__
placeholder with an actual id
from a Post
record in the database, e.g.5
:
mutation {
togglePublishPost(id: 5) {
id
published
}
}
mutation {
incrementPostViewCount(id: __POST_ID__) {
id
viewCount
}
}
Note that you need to replace the __POST_ID__
placeholder with an actual id
from a Post
record in the database, e.g.5
:
mutation {
incrementPostViewCount(id: 5) {
id
viewCount
}
}
{
feed(
searchString: "prisma"
) {
id
title
content
published
}
}
{
feed(
skip: 2
take: 2
orderBy: { updatedAt: desc }
) {
id
updatedAt
title
content
published
}
}
{
postById(id: __POST_ID__ ) {
id
title
content
published
}
}
Note that you need to replace the __POST_ID__
placeholder with an actual id
from a Post
record in the database, e.g.5
:
{
postById(id: 5 ) {
id
title
content
published
}
}
mutation {
deletePost(id: __POST_ID__) {
id
}
}
Note that you need to replace the __POST_ID__
placeholder with an actual id
from a Post
record in the database, e.g.5
:
mutation {
deletePost(id: 5) {
id
}
}
Evolving the application typically requires two steps:
- Migrate your database using Prisma Migrate
- Update your application code
For the following example scenario, assume you want to add a "profile" feature to the app where users can create a profile and write a short bio about themselves.
The first step is to add a new table, e.g. called Profile
, to the database. You can do this by adding a new model to your Prisma schema file file and then running a migration afterwards:
// schema.prisma
model Post {
id Int @default(autoincrement()) @id
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int
}
model User {
id Int @default(autoincrement()) @id
name String?
email String @unique
posts Post[]
+ profile Profile?
}
+model Profile {
+ id Int @default(autoincrement()) @id
+ bio String?
+ userId Int @unique
+ user User @relation(fields: [userId], references: [id])
+}
Once you've updated your data model, you can execute the changes against your database with the following command:
npx prisma migrate dev
You can now use your PrismaClient
instance to perform operations against the new Profile
table. Here are some examples:
const profile = await prisma.profile.create({
data: {
bio: "Hello World",
user: {
connect: { email: "alice@prisma.io" },
},
},
});
const user = await prisma.user.create({
data: {
email: "john@prisma.io",
name: "John",
profile: {
create: {
bio: "Hello World",
},
},
},
});
const userWithUpdatedProfile = await prisma.user.update({
where: { email: "alice@prisma.io" },
data: {
profile: {
update: {
bio: "Hello Friends",
},
},
},
});
- Check out the Prisma docs
- Join our community on Discord to share feedback and interact with other users.
- Subscribe to our YouTube channel for live demos and video tutorials.
- Follow us on X for the latest updates.
- Report issues or ask questions on GitHub.