In this section, you’re going to learn how to connect your GraphQL server to your database using Prisma, which provides the interface to your database. This connection is
implemented via Prisma Client, which you used last chapter for the
The first thing you need to do is import your generated Prisma Client library and wire up the GraphQL server so that you can access the database queries that your new Prisma Client exposes. For this you will use the third argument in a resolver function, the
Remember how we said earlier that all GraphQL resolver functions always receive four arguments? You’ve already learned about
args, now it’s time to get familiar with the
feature is that you can already write to the
context at the moment when the GraphQL server itself is being initialized.
This means that you can attach an instance of Prisma Client to the
context when initializing the server and then access it from inside our resolvers via the
That’s all a bit theoretical, so let’s see how it looks in action 💻
PrismaClientto the resolver context
For code modularity, you will create a dedicated file for initializing the context. This will be called
Now you will create the
context object and attach the
PrismaClient to it.
You’re following a fairly standard TypeScript workflow here of defining a
interface and then creating the object. Let’s go through the numbered comments:
First you have defined the
Context interface, which specifies what objects will be attached to the
context object. Right now it’s just an instance of
PrismaClient, but this can change as the project grows.
You’re exporting the
context object, so that it can be imported and used by the GraphQL server.
Now, you will configure Nexus to know the type of your GraphQL context by adjusting the configuration of