Reputation: 665
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?
Upvotes: 4
Views: 2132
Reputation: 498
Here are a couple of reasons why you want to do it via the context although there is nothing wrong in your approach:
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
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.
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
Upvotes: 6