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 link.findMany()
and link.create()
queries.
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 context
argument.
Remember how we said earlier that all GraphQL resolver functions always receive four arguments? You’ve already learned about parent
and args
, now it’s time to get familiar with the context
argument!
The context
argument is a plain JavaScript object that every resolver in the resolver chain can read from and write to. Thus, it is basically a means for resolvers to communicate. A really helpful
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 context
argument!
That’s all a bit theoretical, so let’s see how it looks in action 💻
PrismaClient
to the resolver contextFor code modularity, you will create a dedicated file for initializing the context. This will be called context.ts
.
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 type
or interface
and then creating the object. Let’s go through the numbered comments:
// 1
: 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. // 2
: 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 makeSchema
in src/schema.ts.