graphql-prisma-select
v0.0.2
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.
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,
})
},
},
}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'],
})Compatibility
Works with:
- Apollo Server
- Mercurius (Fastify)
- GraphQL Yoga
- Any standard GraphQL server that provides
GraphQLResolveInfo.
License
MIT
