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
- Prisma Postgres: A serverless PostgreSQL database built on unikernels.
The example was bootstrapped using the NestJS CLI command nest new nest-graphql.
Download this example:
npx try-prisma@latest --template orm/nest-graphql --install npm --name 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
Create a new Prisma Postgres database by executing:
npx prisma init --db
If you don't have a Prisma Data Platform account yet, or if you are not logged in, the command will prompt you to log in using one of the available authentication providers. A browser window will open so you can log in or create an account. Return to the CLI after you have completed this step.
Once logged in (or if you were already logged in), the CLI will prompt you to:
- Select a region (e.g.
us-east-1) - Enter a project name
After successful creation, you will see output similar to the following:
CLI output
Let's set up your Prisma Postgres database!
? Select your region: ap-northeast-1 - Asia Pacific (Tokyo)
? Enter a project name: testing-migration
β Success! Your Prisma Postgres database is ready β
We found an existing schema.prisma file in your current project directory.
--- Database URL ---
Connect Prisma ORM to your Prisma Postgres database with the provided URL. Add it to your `.env` as `DATABASE_URL`.
--- Next steps ---
Go to https://pris.ly/ppg-init for detailed instructions.
1. Install the `@prisma/adapter-pg` driver adapter and configure your Prisma Client instance
```bash
npm install @prisma/adapter-pg
import { PrismaPg } from '@prisma/adapter-pg'
const pool = new PrismaPg({ connectionString: process.env.DATABASE_URL! })
const prisma = new PrismaClient({ adapter: pool })-
Apply migrations Run the following command to create and apply a migration: npx prisma migrate dev
-
Manage your data View and edit your data locally by running this command: npx prisma studio
...or online in Console: https://console.prisma.io/{workspaceId}/{projectId}/studio
-
Send queries from your app If you already have an existing app with Prisma ORM, you can now run it and it will send queries against your newly created Prisma Postgres instance.
-
Learn more For more info, visit the Prisma Postgres docs: https://pris.ly/ppg-docs
</details>
Locate and copy the database URL provided in the CLI output. Then, create a `.env` file in the project root:
```bash
touch .env
Now, paste the URL into it as a value for the DATABASE_URL environment variable. For example:
# .env
DATABASE_URL=postgres://<username>:<password>@<host>:<port>/<database>Run the following command to create tables in your database. This creates the User and Post tables that are defined in prisma/schema.prisma:
npx prisma migrate dev --name init
Execute the seed file in prisma/seed.ts to populate your database with some sample data, by running:
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",
},
},
},
});If you want to try this example with another database than Postgres, you can adjust the the database connection in prisma/schema.prisma by reconfiguring the datasource block.
Learn more about the different connection configurations in the docs.
Expand for an overview of example configurations with different databases
To use your own PostgreSQL database, set DATABASE_URL to your connection string (e.g. postgres://<username>:<password>@<host>:<port>/<database>). Ensure your app initializes PrismaClient with the @prisma/adapter-pg driver adapter as shown above.
Modify the provider value in the datasource block in the prisma.schema file:
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}Create an .env file and add the SQLite database connection string in it. For example:
DATABASE_URL="file:./dev.db""
Modify the provider value in the datasource block in the prisma.schema file:
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}Create an .env file and add a MySQL database connection string in it. For example:
## This is a placeholder url
DATABASE_URL="mysql://janedoe:mypassword@localhost:3306/notesapi"
Modify the provider value in the datasource block in the prisma.schema file:
datasource db {
provider = "sqlserver"
url = env("DATABASE_URL")
}Create an .env file and add a Microsoft SQL Server database connection string in it. For example:
## This is a placeholder url
DATABASE_URL="sqlserver://localhost:1433;initial catalog=sample;user=sa;password=mypassword;"
Modify the provider value in the datasource block in the prisma.schema file:
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}Create an .env file and add a local MongoDB database connection string in it. For example:
## This is a placeholder url
DATABASE_URL="mongodb://USERNAME:PASSWORD@HOST/DATABASE?authSource=admin&retryWrites=true&w=majority"
- 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.