graphql-prisma-select
v0.0.3
Published
Graphql plugin to ResolveInfo to Prisma Select object
Maintainers
Readme
graphql-prisma-select
A lightweight utility to convert GraphQL ResolveInfo into a Prisma select object. This allows you to automatically fetch only the fields requested by the GraphQL client, resolving the "over-fetching" problem and optimizing database performance.
Features
- Zero Dependencies: Only requires
graphqlas a peer dependency. - Support for Fragments: Handles both inline and named fragments.
- Nested Relations: Recursively builds selection sets for related models.
- Field Exclusion: Easily exclude specific fields (like sensitive data or virtual fields) from the database query.
- JSON Fields Handling: Specifically resolve fields to
trueto avoid Prisma unsupported nested JSON selections errors.
Installation
npm install graphql-prisma-selectyarn add graphql-prisma-selectDon't forget to follow me on GitHub!
Usage
Basic Usage with Prisma
In your resolver, pass the info object to prismaSelect and spread the result into your Prisma query.
import { prismaSelect } from 'graphql-prisma-select'
const resolvers = {
Query: {
users: async (parent, args, context, info) => {
const select = prismaSelect(info)
// Equivalent to: prisma.user.findMany({ select: { id: true, email: true, ... } })
return context.prisma.user.findMany({
...args, // pagination, filtering, etc.
select,
})
},
user: async (parent, { id }, context, info) => {
const select = prismaSelect(info)
return context.prisma.user.findUnique({
where: { id },
select,
})
},
},
}Global Configuration
You can set default options globally, which will be used if not provided in the prismaSelect function call.
import { setGlobalPrismaSelectOptions } from 'graphql-prisma-select'
setGlobalPrismaSelectOptions({
excludeFields: ['password'],
jsonFields: ['metadata'],
})Excluding Fields
You can exclude specific fields from being selected in the database, for example, if they are computed fields or sensitive data that you want to handle manually or via a different mechanism.
const select = prismaSelect(info, {
excludeFields: ['password', 'virtualField'],
})Handling Prisma JSON Fields
Prisma does not support sub-field selections on Json columns. If your GraphQL schema defines a structured type for a JSON column, prismaSelect will attempt to create a nested select object, which causes Prisma to throw an error (not implemented: SelectionSetOnScalar).
To fix this, pass the names of your JSON fields into the jsonFields array option. This forces the utility to select the entire JSON object (true) instead of building a sub-selection.
const select = prismaSelect(info, {
jsonFields: ['attachments', 'metadata', 'config'],
})Compatibility
Works with:
- Apollo Server
- Mercurius (Fastify)
- GraphQL Yoga
- Any standard GraphQL server that provides
GraphQLResolveInfo.
License
MIT
