4

I want to know if is better or there is any difference in use prisma client directly in resolvers or pass it through context.

In the official documentation it is passed through context:

const { prisma } = require('./generated/prisma-client');

const resolvers = {
  Query: {
    feed: (parent, args, context) => {
      return context.prisma.posts({ where: { published: true } })
    }
}

const server = new GraphQLServer({
  typeDefs: './src/schema.graphql',
  resolvers,
  context: {
    prisma,
  },
})

My question is: why prisma client is not used directly in resolvers.

const { prisma } = require('./generated/prisma-client');

const resolvers = {
  Query: {
    feed: (parent, args, context) => {
      return prisma.posts({ where: { published: true } })
    }
}

const server = new GraphQLServer({
  typeDefs: './src/schema.graphql',
  resolvers,
})

Is there anything wrong in this solution?

1 Answers1

6

Here are a couple of reasons why you want to do it via the context although there is nothing wrong in your approach:

  1. When you will write unit tests, you can easily swap the prisma with a mock implementation. Here is an example of this: https://github.com/javascript-af/javascript-af/blob/1e89e5436fbf0d6e3de37f12e6853a8ff6fc7898/packages/backend/tests/utils/gqlTestClient.ts#L12

  2. You can easily pass two instances of prisma this way, like if you want to query data in some other place. You can pass context.db1 and context.db2 by instantiating the Prisma class with two separate endpoints and passing it to the graphql server via two keys in the context object.

  3. In the graphql docs, it is recommended that DB access should be passed via the context. It is always nice to follow the spec: https://graphql.org/learn/execution/#asynchronous-resolvers

Harshit Pant
  • 498
  • 2
  • 10
  • Moreover, you can create the context based on the request and therefore dynamically use of prisma instance or another in a multi-tenant architecture (see [prisma-multi-tenant](https://www.npmjs.com/package/prisma-multi-tenant)) – Errorname Apr 11 '19 at 08:15
  • but how does one get intenseness to work when passing it via context. – Ahmed Eid Sep 13 '19 at 22:27
  • 2
    Context always turns into a mess, and encourages a whole slew of anti-patterns. Over time you end up with so much garbage like "does this variable exist on the context object?", and implementation details leaking out all over the place. I'm just getting started with graph/prisma, but I'd really like to find a better way... – DanG Feb 21 '20 at 23:43