Overview

This upgrade guide describes how to migrate a Node.js project that's based on Prisma 1 and uses prisma-binding to implement a GraphQL server.

The code will be migrated to Nexus and the nexus-schema-plugin-prisma. As opposed to the SDL-first approach that's used with prisma-binding, Nexus follows a code-first approach to construct GraphQL schemas. You can learn about the main differences of these two approaches in this article.

Nexus currently only works with TypeScript, therefore this guide also explains how to migrate from JavaScript to TypeScript. The guide therefore basically assumes a full rewrite of your existing app. If you're currently using JavaScript and want to continue doing so, you can follow the guide to upgrade from prisma-binding to an SDL-first setup.

Note: Because this guide requires a full rewrite, you can only choose this upgrade path if you are following the all-at-once upgrade strategy.

The guide assumes that you already went through the guide for upgrading the Prisma layer. This means you already:

  • installed the Prisma 2.0 CLI
  • created your Prisma 2.0 schema
  • introspected your database and resolved potential schema incompatibilities
  • installed and generated Prisma Client

The guide further assumes that you have a file setup that looks similar to this:

1.
2├── README.md
3├── package.json
4├── prisma
5│ └── schema.prisma
6├── prisma1
7│ ├── datamodel.prisma
8│ └── prisma.yml
9└── src
10 ├── generated
11 │ └── prisma.graphql
12 ├── index.js
13 └── schema.graphql

The important parts are:

  • A folder called with prisma with your Prisma 2.0 schema
  • A folder called src with your application code and a schema called schema.graphql

If this is not what your project structure looks like, you'll need to adjust the instructions in the guide to match your own setup.

1. Installing and configuring Nexus

1.1. Install Nexus dependencies

The first step is to install the Nexus dependency in your project:

1npm install nexus@next

Note: Nexus is currently in a transition phase from a standalone schema construction library to a fully-fledged GraphQL application framework. This guide targets the framework version of Nexus which is currently available under the @next npm tag.

Next, install the the Prisma plugin for Nexus which will allow you to expose Prisma models in your GraphQL API:

1npm install nexus-plugin-prisma

The nexus-plugin-prisma dependency bundles all required Prisma dependencies. You should therefore remove the dependencies that you installed when you upgraded the Prisma layer of your app:

1npm uninstall @prisma/cli @prisma/client

Note however that you can still invoke the Prisma 2.0 CLI with the familiar command:

1npx prisma

1.2. Configure TypeScript

Since you'll be using TypeScript in this guide, you need to add the required dependencies:

1npm install typescript ts-node --save-dev

Create a new file called tsconfig.json in the root directory of your project:

1touch tsconfig.json

Now add the following contents to the new file:

1{
2 "compilerOptions": {
3 "skipLibCheck": true,
4 "strict": true,
5 "rootDir": "src",
6 "noEmit": true,
7 "typeRoots": ["node_modules/@types","types"],
8 "plugins": [{ "name": "nexus/typescript-language-service" }]
9 },
10 "include": ["src", "types.d.ts"]
11}

1.3. Create your basic Nexus setup

Create the root source file of your API called app.ts inside the src directory:

1touch src/app.ts

Now add the following setup code to it:

1import { settings, use } from 'nexus'
2import { prisma } from 'nexus-plugin-prisma'
3
4use(
5 prisma({
6 migrations: false,
7 features: { crud: true },
8 }),
9)
10
11settings.change({
12 server: {
13 startMessage: (info) => {
14 settings.original.server.startMessage(info)
15 },
16 },
17 schema: {
18 generateGraphQLSDLFile: './src/generated/nexus.graphql'
19 }
20})

There are two main things to note about this setup:

  • When adding the nexus-plugin-prisma via Nexus' use() function, you're disabling Prisma Migrate and enabling the auto-generation of CRUD resolvers via t.crud.
  • You'll be generating the SDL-version of your GraphQL schema nexus.graphql inside ./src/generated.

Also, adjust the scripts section inside your package.json to include the following commands:

1{
2 "scripts": {
+ "dev": "nexus dev",
+ "build": "nexus build",
+ "start": "node node_modules/.build"
6 }
7}

The dev script starts a development server that you always should have running in the background when developing your app.

You can start the development server using the following command:

1npm run dev

You should see the following CLI output:

1589 ▲ nexus:schema Your GraphQL schema is empty. This is normal if you have not defined any GraphQL types yet. If you did however, check that your files are contained in the same directory specified in the `rootDir` property of your tsconfig.json file.
2 3 ● nexus:server listening -- url: 'http://localhost:4000/'

Your GraphQL server is now running, but there's no actual GraphQL schema connected to it yet. In the following steps, we'll explain how you can migrate your existing SDL-first GraphQL schema that's implemented with prisma-binding to an equivalent setup using Nexus.

2. Create your GraphQL types

The next step of the upgrade process is to create your GraphQL types. In this case, your GraphQL types will mirror the Prisma models (as it likely was the case in your prisma-binding setup as well). If a GraphQL type deviates from a Prisma model, you'll be able to easily adjust the exposed GraphQL type accordingly using the Nexus API.

For the purpose of this guide, you'll keep all the code in a single file. However, you can structure the files to your personal preference and import accordingly.

Create a new file called graphql.ts right next to app.ts:

1touch src/graphql.ts

In Nexus, GraphQL types are defined via the objectType function that's exposed by the main schema object. Import schema and then start with the skeleton for your first GraphQL type. In this case, we're starting by mapping Prisma's User model to GraphQL:

1import { schema } from 'nexus'
2
3schema.objectType({
4 name: 'User',
5 definition(t) {
6 // the fields of the type will be defined here
7 },
8})

With this code in place, you can start exposing the fields of the User model one by one. You can use your editor's autocompletion to save some typing. Inside the body of the definition function, type t.model. and then hit CTRL+SPACE. This will bring up the autocompletion and suggest all fields that are defined on the User model:

Note that the model property on t is provided by the nexus-plugin-prisma. It leverages the type information from your Prisma schema and allows you to easily expose them via GraphQL.

In that manner, you can start completing your object type definition until you exposed all the fields of the model:

1schema.objectType({
2 name: 'User',
3 definition(t) {
4 t.model.id()
5 t.model.email()
6 t.model.name()
7 t.model.jsonData()
8 t.model.role()
9 t.model.profile()
10 t.model.posts()
11 },
12})

At this point, any relation fields might give you TypeScript errors (in this case, that would be profile and posts which both point to other object types). That's expected, these errors will resolve automatically after you've added the remaining types.

Note: Be sure to have your Nexus development server that you started with npm run dev running all the time. It constantly updates the generated Nexus types that enable the autocompletion in the background as you save a file.

Note that the t.model.posts relation exposes a list of Post objects. By default, Nexus exposes only pagination properties for that list – if you want to add ordering and filtering for that relation as well, you'll need to explicitly enable those:

1schema.objectType({
2 name: 'User',
3 definition(t) {
4 t.model.id()
5 t.model.email()
6 t.model.name()
7 t.model.jsonData()
8 t.model.role()
9 t.model.profile()
+ t.model.posts({
+ filtering: true,
+ ordering: true,
+ })
14 },
15})

Note: If you have one or more fields of type Json on any of your Prisma models, enabling filtering currently produces an error. As a workaround, you can temporarily comment out these field(s) in your Prisma schema.

Once you're done with the first type, you can start defining the remaining ones.

To expose all sample Prisma models with Nexus, the following code is needed:

1schema.objectType({
2 name: 'User',
3 definition(t) {
4 t.model.id()
5 t.model.email()
6 t.model.name()
7 t.model.jsonData()
8 t.model.role()
9 t.model.profile()
10 t.model.posts({
11 filtering: true,
12 ordering: true,
13 })
14 },
15})
16
17schema.objectType({
18 name: 'Post',
19 definition(t) {
20 t.model.id()
21 t.model.createdAt()
22 t.model.updatedAt()
23 t.model.title()
24 t.model.content()
25 t.model.published()
26 t.model.author()
27 t.model.authorId()
28 t.model.categories({
29 filtering: true,
30 ordering: true,
31 })
32 },
33})
34
35schema.objectType({
36 name: 'Profile',
37 definition(t) {
38 t.model.id()
39 t.model.bio()
40 t.model.user()
41 t.model.owner()
42 },
43})
44
45schema.objectType({
46 name: 'Category',
47 definition(t) {
48 t.model.id()
49 t.model.name()
50 t.model.posts({
51 filtering: true,
52 ordering: true,
53 })
54 },
55})

You can view the current version of your GraphQL schema in SDL in the generated GraphQL schema file in ./src/generated/nexus.graphql.

3. Migrate GraphQL operations

As a next step, you can start migrating all the GraphQL queries and mutations from the "previous" GraphQL API to the new one that's built with Nexus.

For this guide, the following sample GraphQL schema will be used:

1# import Post from './generated/prisma.graphql'
2# import User from './generated/prisma.graphql'
3# import Category from './generated/prisma.graphql'
4
5input UserUniqueInput {
6 id: String
7 email: String
8}
9
10type Query {
11 posts(searchString: String): [Post!]!
12 user(userUniqueInput: UserUniqueInput!): User
13 users(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [User]!
14}
15
16type Mutation {
17 createUser(data: UserCreateInput!): User!
18 createDraft(title: String!, content: String, authorId: ID!): Post
19 updateBio(userUniqueInput: UserUniqueInput!, bio: String!): User
20 addPostToCategories(postId: String!, categoryIds: [String!]!): Post
21}

3.1. Migrate GraphQL queries

In this section, you'll migrate all GraphQL queries from prisma-binding to Nexus.

3.1.1. Define the Query type

The first step to migrate any queries is to define the Query type of your GraphQL API. Once that's done, you can gradually add operations to it. Add the following definition to graphql.ts:

1schema.queryType({
2 definition(t) {
3 // your GraphQL queries + resolvers will be defined here
4 }
5})

Note that the Nexus API can seem a bit confusing at first. The code above is actually equivalent to writing the following:

1schema.queryType({
2 definition: t => {
3 // your GraphQL queries + resolvers will be defined here
4 }
5})

However, the first version of the two is the common conventions for Nexus, so it'll be used throughout this guide.

3.1.2. Migrate the users query (which uses forwardTo)

In our sample API, the users query from the sample GraphQL schema is defined and implemented as follows.

SDL schema definition with prisma-binding
1type Query {
2 users(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [User]!
3 # ... other queries
4}
Resolver implementation with prisma-binding
1const resolvers = {
2 Query: {
3 users: forwardTo('prisma'),
4 // ... other resolvers
5 }
6}

To mirror the same behaviour with Nexus, you can use the crud property on the t variable inside the definition function.

Similar to model, this property is available because you're using the nexus-prisma-plugin which leverages type information from your Prisma models and auto-generates resolvers under the hood. The crud property also supports autocompletion, so you can explore all available queries in your editor again:

Forwarding the query with the nexus-prisma-plugin

To add the users query to your GraphQL API, add the following lines to the query type definition:

1schema.queryType({
2 definition(t) {
+ t.crud.users({
+ filtering: true,
+ ordering: true,
+ })
7 }
8})

If you have the Nexus development server running, you can save the file and your GraphQL API will be updated to expose the new users query. You can also observe this by looking at the Query type inside the generated nexus.graphql file:

1type Query {
2 users(after: UserWhereUniqueInput, before: UserWhereUniqueInput, first: Int, last: Int, orderBy: UserOrderByInput, skip: Int, where: UserWhereInput): [User!]!
3}

You can now write your first query against the new API, e.g.:

1{
2 users {
3 id
4 name
5 profile {
6 id
7 bio
8 }
9 posts {
10 id
11 title
12 categories {
13 id
14 name
15 }
16 }
17 }
18}

If your application exposes all CRUD operations from Prisma using forwardTo, you can now continue adding all remaining ones using the same approach via t.crud. To learn how "custom" queries can be defined and resolved using Nexus, move on to the next sections.

3.1.3. Migrate the posts(searchString: String): [Post!]! query

The posts query is defined and implemented as follows.

SDL schema definition with prisma-binding
1type Query {
2 posts(searchString: String): [Post!]!
3 # ... other queries
4}
Resolver implementation with prisma-binding
1const resolvers = {
2 Query: {
3 posts: (_, args, context, info) => {
4 return context.prisma.query.posts(
5 {
6 where: {
7 OR: [
8 { title_contains: args.searchString },
9 { content_contains: args.searchString },
10 ],
11 },
12 },
13 info,
14 )
15 },
16 // ... other resolvers
17 }
18}
Code-first schema definition with nexus

To get the same behaviour with Nexus, you'll need to add a t.field definition to the queryType:

1schema.queryType({
2 definition(t) {
3 // ... previous queries
4
+ t.list.field('posts', {
+ type: 'Post',
+ nullable: false,
+ args: { searchString: schema.stringArg() }
+ })
10 }
11})

If you look at the generated SDL version of your GraphQL schema inside nexus.graphql, you'll notice that this has added the correct definition to your GraphQL schema already:

1type Query {
2 posts(searchString: String): [Post!]!
3 users(after: UserWhereUniqueInput, before: UserWhereUniqueInput, first: Int, last: Int, orderBy: UserOrderByInput, skip: Int, where: UserWhereInput): [User!]!
4}

You can even send the respective query via the GraphQL Playground already:

1{
2 posts {
3 id
4 title
5 }
6}

However, the response of such a query will always be:

1{
2 "data": {
3 "posts": null
4 }
5}
Resolver implementation with nexus

That's because you're still missing the resolver implementation for that query. You can add the resolver with Nexus as follows:

1schema.queryType({
2 definition(t) {
3 // ... previous queries
4
5 t.list.field('posts', {
6 type: 'Post',
7 nullable: false,
8 args: { searchString: schema.stringArg() },
+ resolve: (_, args, context) => {
+ return context.db.post.findMany({
+ where: {
+ OR: [{
+ title: { contains: args.searchString }
+ }, {
+ content: { contains: args.searchString }
+ }]
+ }
+ })
+ }
20 })
21 }
22})

If you're re-sending the same query from before, you'll find that it now returns actual data instead of null.

Note that the db object that's attached to the context argument represents your PrismaClient instance that you can use to send queries to your database.

3.1.3. Migrate the user(uniqueInput: UserUniqueInput): User query

In our sample app, the user query is defined and implemented as follows.

SDL schema definition with prisma-binding
1type Query {
2 user(userUniqueInput: UserUniqueInput): User
3 # ... other queries
4}
5
6input UserUniqueInput {
7 id: String
8 email: String
9}

Note that this is a bit of a contrived example to demonstrate usage of input types with Nexus.

Resolver implementation with prisma-binding
1const resolvers = {
2 Query: {
3 user: (_, args, context, info) => {
4 return context.prisma.query.user(
5 {
6 where: args.userUniqueInput,
7 },
8 info,
9 )
10 },
11 // ... other resolvers
12 }
13}
Code-first schema definition with nexus

To get the same behaviour with Nexus, you'll need to add a t.field definition to the queryType and define an inputObjectType that includes the two @unique fields of your User model:

+schema.inputObjectType({
+ name: 'UserUniqueInput',
+ definition(t) {
+ t.string('id')
+ t.string('email')
+ },
+})
8
9schema.queryType({
10 definition(t) {
11 // ... previous queries
12
+ t.field('user', {
+ type: 'User',
+ args: {
+ userUniqueInput: schema.arg({
+ type: 'UserUniqueInput',
+ nullable: false,
+ })
+ }
+ })
22 }
23})

If you look at the generated SDL version of your GraphQL schema inside nexus.graphql, you'll notice that this change already added the correct definition to your GraphQL schema:

1type Query {
2 posts(searchString: String): [Post!]
3 user(userUniqueInput: UserUniqueInput!): User
4 users(after: UserWhereUniqueInput, before: UserWhereUniqueInput, first: Int, last: Int, orderBy: UserOrderByInput, skip: Int, where: UserWhereInput): [User!]!
5}
6
7 input UserUniqueInput {
8 email: String
9 id: String
10 }

You can even send the respective query via the GraphQL Playground already:

1{
2 user(userUniqueInput: { email: "alice@prisma.io" }) {
3 id
4 name
5 }
6}

However, the response of such a query will always be:

1{
2 "data": {
3 "user": null
4 }
5}
Code-first resolver implementation with nexus

That's because you're still missing the resolver implementation for that query. You can add the resolver with Nexus as follows:

1schema.inputObjectType({
2 name: 'UserUniqueInput',
3 definition(t) {
4 t.string('id')
5 t.string('email')
6 },
7})
8
9schema.queryType({
10 definition(t) {
11 // ... previous queries
12
13 t.field('user', {
14 type: 'User',
15 nullable: true,
16 args: {
17 userUniqueInput: schema.arg({
18 type: 'UserUniqueInput',
19 nullable: false,
20 })
21 },
+ resolve: (_, args, context) => {
+ return context.db.user.findOne({
+ where: {
+ id: args.userUniqueInput?.id,
+ email: args.userUniqueInput?.email
+ }
+ })
+ }
30 })
31 },
32 }
33})

If you're re-sending the same query from before, you'll find that it now returns actual data instead of null.

3.2. Migrate GraphQL mutations

In this section, you'll migrate the GraphQL mutations from the sample schema to the Nexus.

3.2.1. Define the Mutation type

The first step to migrate any mutations is to define the Mutation type of your GraphQL API. Once that's done, you can gradually add operations to it. Add the following definition to graphql.ts:

1schema.mutationType({
2 definition(t) {
3 // your GraphQL mutations + resolvers will be defined here
4 }
5})

3.2.2. Migrate the createUser mutation (which uses forwardTo)

In the sample app, the createUser mutation from the sample GraphQL schema is defined and implemented as follows.

SDL schema definition with prisma-binding
1type Mutation {
2 createUser(data: UserCreateInput!): User!
3 # ... other mutations
4}
Resolver implementation with prisma-binding
1const resolvers = {
2 Mutation: {
3 createUser: forwardTo('prisma'),
4 // ... other resolvers
5 }
6}

Similar to forwarding GraphQL queries, you can use the crud property on the t variable inside the definition function in order to expose full CRUD capabilities for Prisma models.

Similar to model, this property is available because you're using the nexus-prisma-plugin which leverages type information from your Prisma models and auto-generates resolvers under the hood. The crud property supports autocompletion when defining mutations as well, so you can explore all available operations in your editor again:

Forwarding the mutation with the nexus-prisma-plugin

To add the createUser mutation to your GraphQL API, add the following lines to the query type definition:

1schema.mutationType({
2 definition(t) {
+ t.crud.createOneUser({
+ alias: 'createUser',
+ })
6 }
7})

Note that the default name for the mutation in your GraphQL schema is createOneUser (named after the function which is exposed by t.crud). In order to rename it to createUser, you need to provide the alias property.

If you have the Nexus development server running, you can save the file and your GraphQL API will be updated to expose the new createUser mutation. You can also observe this by looking at the Mutation type inside the generated nexus.graphql file:

1type Mutation {
2 createUser(data: UserCreateInput!): User!
3}

You can now write your first mutation against the new API, e.g.:

1mutation {
2 createUser(data: {
3 name: "Alice",
4 email: "alice@prisma.io"
5 }) {
6 id
7 }
8}

If your application exposes all CRUD operations from Prisma using forwardTo, you can now continue adding all remaining ones using the same approach via t.crud. To learn how "custom" mutations can be defined and resolved using Nexus, move on to the next sections.

3.2.3. Migrate the createDraft(title: String!, content: String, authorId: String!): Post! query

In the sample app, the createDraft mutation is defined and implemented as follows.

SDL schema definition with prisma-binding
1type Mutation {
2 createDraft(title: String!, content: String, authorId: String!): Post!
3 # ... other mutations
4}
Resolver implementation with prisma-binding
1const resolvers = {
2 Mutation: {
3 createDraft: (_, args, context, info) => {
4 return context.prisma.mutation.createPost(
5 {
6 data: {
7 title: args.title,
8 content: args.content,
9 author: {
10 connect: {
11 id: args.authorId,
12 },
13 },
14 },
15 },
16 info,
17 )
18 },
19 // ... other resolvers
20 }
21}
Code-first schema definition with nexus

To get the same behaviour with Nexus, you'll need to add a t.field definition to the mutationType:

1schema.mutationType({
2 definition(t) {
3 // ... previous mutations
4
+ t.field('createDraft', {
+ type: 'Post',
+ args: {
+ title: schema.stringArg({ nullable: false }),
+ content: schema.stringArg(),
+ authorId: schema.stringArg({ nullable: false }),
+ }
+ })
13 }
14})

If you look at the generated SDL version of your GraphQL schema inside nexus.graphql, you'll notice that this has added the correct definition to your GraphQL schema already:

1type Mutation {
2 createUser(data: UserCreateInput!): User!
3 createDraft(title: String!, content: String, authorId: String!): Post!
4}

You can even send the respective mutation via the GraphQL Playground already:

1mutation {
2 createDraft(
3 title: "Hello World",
4 authorId: "__AUTHOR_ID__"
5 ) {
6 id
7 published
8 author {
9 id
10 name
11 }
12 }
13}

However, the response of such a mutation will always be:

1{
2 "data": {
3 "createDraft": null
4 }
5}
Resolver implementation with nexus

That's because you're still missing the resolver implementation for that mutation. You can add the resolver with Nexus as follows:

1schema.mutationType({
2 definition(t) {
3 // ... previous mutations
4
5 t.field('createDraft', {
6 type: 'Post',
7 args: {
8 title: schema.stringArg({ nullable: false }),
9 content: schema.stringArg(),
10 authorId: schema.stringArg({ nullable: false }),
11 },
+ resolve: (_, args, context) => {
+ return context.db.post.create({
+ data: {
+ title: args.title,
+ content: args.content,
+ author: {
+ connect: { id: args.authorId }
+ }
+ }
+ })
+ }
23 })
24 }
25})

If you're re-sending the same query from before, you'll find that it now returns actual data instead of null.

3.2.4. Migrate the updateBio(bio: String, userUniqueInput: UserUniqueInput!): User mutation

In the sample app, the updateBio mutation is defined and implemented as follows.

SDL schema definition with prisma-binding
1type Mutation {
2 updateBio(bio: String!, userUniqueInput: UserUniqueInput!): User
3 # ... other mutations
4}
Resolver implementation with prisma-binding
1const resolvers = {
2 Mutation: {
3 updateBio: (_, args, context, info) => {
4 return context.prisma.mutation.updateUser(
5 {
6 data: {
7 profile: {
8 update: { bio: args.bio }
9 }
10 },
11 where: { id: args.userId }
12 },
13 info,
14 )
15 },
16 // ... other resolvers
17 }
18}
Code-first schema definition with nexus

To get the same behaviour with Nexus, you'll need to add a t.field definition to the mutationType:

1schema.mutationType({
2 definition(t) {
3 // ... previous mutations
4
+ t.field('updateBio', {
+ type: 'User',
+ args: {
+ userUniqueInput: schema.arg({
+ type: 'UserUniqueInput',
+ nullable: false
+ }),
+ bio: schema.stringArg({ nullable: false })
+ },
+ })
15 }
16})

If you look at the generated SDL version of your GraphQL schema inside nexus.graphql, you'll notice that this has added the correct definition to your GraphQL schema already:

1type Mutation {
2 createUser(data: UserCreateInput!): User!
3 createDraft(title: String!, content: String, authorId: String!): Post!
4 updateBio(bio: String!, userUniqueInput: UserUniqueInput!): User
5}

You can even send the respective mutation via the GraphQL Playground already:

1mutation {
2 updateBio(
3 userUniqueInput: {
4 email: "alice@prisma.io"
5 }
6 bio: "I like turtles"
7 ){
8 id
9 name
10 profile {
11 id
12 bio
13 }
14 }
15}

However, the response of such a mutation will always be:

1{
2 "data": {
3 "updateBio": null
4 }
5}
Resolver implementation with nexus

That's because you're still missing the resolver implementation for that query. You can add the resolver with Nexus as follows:

1schema.mutationType({
2 definition(t) {
3 // ... previous mutations
4
5 t.field('updateBio', {
6 type: 'User',
7 args: {
8 userUniqueInput: schema.arg({
9 type: 'UserUniqueInput',
10 nullable: false
11 }),
12 bio: schema.stringArg()
13 },
+ resolve: (_, args, context) => {
+ return context.db.user.update({
+ where: {
+ id: args.userUniqueInput?.id,
+ email: args.userUniqueInput?.email
+ },
+ data: {
+ profile: {
+ create: { bio: args.bio }
+ }
+ }
+ })
26 }
27 }
28})

If you're re-sending the same query from before, you'll find that it now returns actual data instead of null.

3.2.5. Migrate the addPostToCategories(postId: String!, categoryIds: [String!]!): Post mutation

In our sample app, the addPostToCategories mutation is defined and implemented as follows.

SDL schema definition with prisma-binding
1type Mutation {
2 addPostToCategories(postId: String!, categoryIds: [String!]!): Post
3 # ... other mutations
4}
Resolver implementation with prisma-binding
1const resolvers = {
2 Mutation: {
3 addPostToCategories: (_, args, context, info) => {
4 const ids = args.categoryIds.map(id => ({ id }))
5 return context.prisma.mutation.updatePost(
6 {
7 data: {
8 categories: {
9 connect: ids
10 }
11 },
12 where: {
13 id: args.postId
14 }
15 },
16 info,
17 )
18 },
19 // ... other resolvers
20 }
21}
Code-first schema definition with nexus

To get the same behaviour with Nexus, you'll need to add a t.field definition to the mutationType:

1schema.mutationType({
2 definition(t) {
3 // ... mutations from before
4
+ t.field('addPostToCategories', {
+ type: 'Post',
+ args: {
+ postId: schema.stringArg({ nullable: false }),
+ categoryIds: schema.stringArg({
+ list: true,
+ nullable: false
+ }),
+ },
+ })
15 }
16})

If you look at the generated SDL version of your GraphQL schema inside nexus.graphql, you'll notice that this has added the correct definition to your GraphQL schema already:

1type Mutation {
2 createUser(data: UserCreateInput!): User!
3 createDraft(title: String!, content: String, authorId: String!): Post!
4 updateBio(bio: String, userUniqueInput: UserUniqueInput!): User
5 addPostToCategories(postId: String!, categoryIds: [String!]!): Post
6}

You can even send the respective query via the GraphQL Playground already:

1mutation {
2 addPostToCategories(
3 postId: "__AUTHOR_ID__"
4 categoryIds: [
5 "__CATEGORY_ID_1__",
6 "__CATEGORY_ID_2__",
7 ]
8 ) {
9 id
10 title
11 categories {
12 id
13 name
14 }
15 }
16}

However, the response of such a mutation will always be:

1{
2 "data": {
3 "addPostToCategories": null
4 }
5}
Resolver implementation with nexus

That's because you're still missing the resolver implementation for that query. You can add the resolver with Nexus as follows:

1schema.mutationType({
2 definition(t) {
3 // ... mutations from before
4 t.field('addPostToCategories', {
5 type: 'Post',
6 args: {
7 postId: schema.stringArg({ nullable: false }),
8 categoryIds: schema.stringArg({
9 list: true,
10 nullable: false
11 }),
12 },
+ resolve: (_, args, context) => {
+ const ids = args.categoryIds.map(id => ({ id }))
+ return context.db.post.update({
+ where: {
+ id: args.postId
+ },
+ data: {
+ categories: { connect: ids }
+ }
+ })
+ }
24 })
25 }
26})

If you're re-sending the same query from before, you'll find that it now returns actual data instead of null.

4. Cleaning up

Since the entire app has now been upgrade to Prisma 2.0 and Nexus, you can delete all unnecessary files and remove the no longer needed dependencies.

4.1. Clean up npm dependencies

You can start by removing npm dependencies that were related to the Prisma 1 setup:

1npm uninstall graphql-cli graphql-yoga prisma-binding prisma1

4.2. Delete unused files

Next, delete the files of your Prisma 1 setup:

1rm prisma1/datamodel.prisma prisma1/prisma.yml

You can also delete any remaining .js files, the schema.graphql and prisma.graphql files.

4.3. Stop the Prisma server

Finally, you can stop running your Prisma server.

Edit this page on Github