This example shows how to implement a GraphQL server with TypeScript based on Prisma Client, apollo-server. It is based on a SQLite database - you can find the database file with some dummy data at ./prisma/dev.db
.
Download this example:
curl https://codeload.github.com/prisma/prisma-examples/tar.gz/latest | tar -xz --strip=2 prisma-examples-latest/typescript/graphql-typegraphql
Install npm dependencies:
cd graphql-typegraphql
npm install
Alternative: Clone the entire repo
Clone this repository:
git clone [email protected]:prisma/prisma-examples.git --depth=1
Install npm dependencies:
cd prisma-examples/typescript/graphql-typegraphql
npm install
Run the following command to create your SQLite database file. This also creates the User
and Post
tables that are defined in prisma/schema.prisma
:
npx prisma migrate dev --name init
Now, seed the database with the sample data in prisma/seed.ts
by running the following command:
npx prisma db seed --preview-feature
Launch your GraphQL server with this command:
npm run dev
Navigate to http://localhost:4000 in your browser to explore the API of your GraphQL server in a GraphQL Playground.
The schema specifies the API operations of your GraphQL server. TypeGraphQL allows you to define a schema using TypeScript classes and decorators. The schema is generated at runtime, and is defined by the following classes:
./src/PostResolvers.ts
./src/UserResolvers.ts
./src/User.ts
./src/Post.ts
./src/UserCreateInput.ts
./src/PostCreateInput.ts
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
mutation {
signupUser(data: { name: "Sarah", email: "[email protected]" }) {
id
}
}
mutation {
createDraft(
data: {
title: "Join the Prisma Slack"
content: "https://slack.prisma.io"
email: "[email protected]"
}
) {
id
published
}
}
mutation {
publish(id: __POST_ID__) {
id
published
}
}
Note: You need to replace the
__POST_ID__
-placeholder with an actualid
from aPost
item. You can find one e.g. using thefilterPosts
-query.
{
filterPosts(searchString: "graphql") {
id
title
content
published
author {
id
name
email
}
}
}
{
post(id: __POST_ID__) {
id
title
content
published
author {
id
name
email
}
}
}
Note: You need to replace the
__POST_ID__
-placeholder with an actualid
from aPost
item. You can find one e.g. using thefilterPosts
-query.
mutation {
deleteOnePost(id: __POST_ID__) {
id
}
}
Note: You need to replace the
__POST_ID__
-placeholder with an actualid
from aPost
item. You can find one e.g. using thefilterPosts
-query.
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. Those operations can be used to implement new queries and mutations in the GraphQL API.
You can use TypeGraphQL to expose the new Profile
model. Create a new file named src\Profile.ts
and add the following code:
import 'reflect-metadata'
import { ObjectType, Field, ID } from 'type-graphql'
import { User } from './User'
@ObjectType()
export class Profile {
@Field((type) => ID)
id: number
@Field((type) => User, { nullable: true })
user?: User | null
@Field((type) => String, { nullable: true })
bio?: string | null
}
Create a new file named src\ProfileCreateInput.ts
with the following code:
import 'reflect-metadata'
import { ObjectType, Field, ID, InputType } from 'type-graphql'
import { User } from './User'
@InputType()
export class ProfileCreateInput {
@Field((type) => String, { nullable: true })
bio?: string | null
}
Add the profile
field to src\User.ts
and import the Profile
class.
@Field(type => Profile, { nullable: true })
profile?: Profile | null;
Add the profile
field to src\UserCreateInput.ts
and import the ProfileCreateInput
class:
@Field(type => ProfileCreateInput, { nullable: true })
profile?: ProfileCreateInput | null;
Extend the src\UserResolver.ts
class with an additional field resolver:
@FieldResolver()
async profile(@Root() user: User, @Ctx() ctx: Context): Promise<Profile> {
return (await ctx.prisma.user.findUnique({
where: {
id: user.id
}
}).profile())!
}
Update the signupUser
mutation to include the option to create a profile when you sign up a new user:
@Mutation(returns => User)
async signupUser(
@Arg("data") data: UserCreateInput,
@Ctx() ctx: Context): Promise<User> {
try {
return await ctx.prisma.user.create({
data: {
email: data.email,
name: data.name,
profile: {
create: {
bio: data.bio?.bio
}
}
}
});
}
catch (error) {
throw error;
}
}
Run the following mutation to create a user with a profile:
mutation {
signupUser(
data: {
email: "[email protected]"
profile: {
bio: "Sometimes I'm an Icelandic volcano, sometimes I'm a dragon from a book."
}
}
) {
id
email
posts {
title
}
profile {
id
bio
}
}
}
Run the following query to return a user and their profile:
query {
user(id: 1) {
email
profile {
id
bio
}
posts {
title
content
}
}
}
As the Prisma Client API was updated, you can now also invoke "raw" operations via prisma.profile
directly.
const profile = await prisma.profile.create({
data: {
bio: 'Hello World',
user: {
connect: { email: '[email protected]' },
},
},
})
const user = await prisma.user.create({
data: {
email: '[email protected]',
name: 'John',
profile: {
create: {
bio: 'Hello World',
},
},
},
})
const userWithUpdatedProfile = await prisma.user.update({
where: { email: '[email protected]' },
data: {
profile: {
update: {
bio: 'Hello Friends',
},
},
},
})
If you want to try this example with another database than SQLite, 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
For PostgreSQL, the connection URL has the following structure:
datasource db {
provider = "postgresql"
url = "postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA"
}
Here is an example connection string with a local PostgreSQL database:
datasource db {
provider = "postgresql"
url = "postgresql://janedoe:mypassword@localhost:5432/notesapi?schema=public"
}
For MySQL, the connection URL has the following structure:
datasource db {
provider = "mysql"
url = "mysql://USER:PASSWORD@HOST:PORT/DATABASE"
}
Here is an example connection string with a local MySQL database:
datasource db {
provider = "mysql"
url = "mysql://janedoe:mypassword@localhost:3306/notesapi"
}
Here is an example connection string with a local Microsoft SQL Server database:
datasource db {
provider = "sqlserver"
url = "sqlserver://localhost:1433;initial catalog=sample;user=sa;password=mypassword;"
}
Because SQL Server is currently in Preview, you need to specify the previewFeatures
on your generator
block:
generator client {
provider = "prisma-client-js"
previewFeatures = ["microsoftSqlServer"]
}
- Check out the Prisma docs
- Share your feedback in the
prisma2
channel on the Prisma Slack - Create issues and ask questions on GitHub
- Watch our biweekly "What's new in Prisma" livestreams on Youtube