npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@k0lyan/nestjs-prisma-graphql-generator

v0.8.19

Published

Prisma generator for NestJS 11 GraphQL with optimized query building from GraphQL selections

Readme

NestJS Prisma GraphQL Generator

A Prisma generator that produces optimized NestJS 11 GraphQL resolvers, object types, input types, and args from Prisma models.

Key Features

  • 🚀 Optimized Queries - No N+1 problems! Uses GraphQL selection analysis to build minimal Prisma queries
  • 📦 Full CRUD - Generates complete CRUD resolvers (findMany, findUnique, create, update, delete, etc.)
  • 🎯 NestJS Native - Uses @nestjs/graphql decorators (@ObjectType, @Resolver, @Query, @Mutation)
  • 🔧 Configurable - Customize output directories, select specific blocks to generate
  • 📝 Type-Safe - Full TypeScript support with proper type inference

Why This Generator?

Traditional GraphQL resolvers use @ResolveField() for relations, causing N+1 queries:

// ❌ SLOW - Causes N+1 queries on large lists
@ResolveField(() => [Post])
async posts(@Parent() user: User) {
  return this.prisma.post.findMany({ where: { authorId: user.id } });
}

This generator produces resolvers that analyze the GraphQL query and build a single optimized Prisma query:

// ✅ FAST - Single query with all needed data
@Query(() => [User])
async users(@Info() info: GraphQLResolveInfo, @Args() args: FindManyUserArgs) {
  const select = transformInfoIntoPrismaArgs(info);
  return this.prisma.user.findMany({ ...args, ...select });
}

Installation

npm install nestjs-prisma-graphql-generator

Usage

Add the generator to your schema.prisma:

generator client {
  provider = "prisma-client-js"
}

generator nestjsGraphql {
  provider = "nestjs-prisma-graphql-generator"
  output   = "../src/generated/graphql"
}

model User {
  id    String @id @default(cuid())
  email String @unique
  name  String?
  posts Post[]
}

model Post {
  id       String @id @default(cuid())
  title    String
  author   User   @relation(fields: [authorId], references: [id])
  authorId String
}

Run Prisma generate:

npx prisma generate

Generated Output

With groupByModel = "true" (default), files are grouped by model:

src/generated/graphql/
├── models/
│   ├── User/
│   │   ├── model.ts        # @ObjectType class
│   │   ├── inputs.ts       # @InputType classes for this model
│   │   ├── args.ts         # @ArgsType classes for this model
│   │   ├── resolver.ts     # CRUD resolver (queries + mutations)
│   │   ├── aggregations.ts # Aggregate/GroupBy types and resolver
│   │   └── index.ts
│   ├── Post/
│   │   └── ...
│   └── index.ts
├── enums/                  # GraphQL enums
├── common/                 # Shared types (AffectedRows, filters)
├── helpers.ts              # Runtime helpers
└── index.ts

Using Generated Code

1. Setup GraphQL Module

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver } from '@nestjs/apollo';
import { PrismaService } from './prisma.service';
import {
  UserResolver,
  UserAggregateResolver,
  PostResolver,
  PostAggregateResolver,
} from './generated/graphql/models';

@Module({
  imports: [
    GraphQLModule.forRoot({
      driver: ApolloDriver,
      autoSchemaFile: true,
      context: ({ req }) => ({
        prisma: new PrismaService(), // Or inject via DI
      }),
    }),
  ],
  providers: [
    PrismaService,
    UserResolver,
    UserAggregateResolver,
    PostResolver,
    PostAggregateResolver,
  ],
})
export class AppModule {}

2. Query with Relations

query {
  users {
    id
    name
    posts {
      id
      title
    }
  }
}

This generates a single Prisma query:

prisma.user.findMany({
  select: {
    id: true,
    name: true,
    posts: {
      select: {
        id: true,
        title: true,
      },
    },
  },
});

Configuration Options

generator nestjsGraphql {
  provider           = "nestjs-prisma-graphql-generator"
  output             = "../src/generated/graphql"

  // Generate only specific blocks
  emitOnly           = "models,resolvers"

  // Disable resolver generation
  generateResolvers  = "true"

  // Custom Prisma client import path
  prismaClientPath   = "@prisma/client"

  // Add prefix/suffix to type names
  typePrefix         = ""
  typeSuffix         = ""

  // Use require() for relation imports (helps with circular deps in large projects)
  // Default: true
  useRequireForRelations = "true"

  // Re-export enums from Prisma client instead of generating new ones
  // This avoids duplicate enum definitions and ensures consistency
  // Default: false
  usePrismaEnums     = "false"

  // Custom output directories
  modelsOutput       = "models"
  inputsOutput       = "inputs"
  argsOutput         = "args"
  enumsOutput        = "enums"
  resolversOutput    = "resolvers"
}

Generated Operations

For each model, the following operations are generated:

Queries

  • findMany{Model} - List with filtering, sorting, pagination
  • findUnique{Model} - Get single by unique field
  • findFirst{Model} - Get first matching record
  • aggregate{Model} - Aggregations
  • groupBy{Model} - Group by fields
  • {model}Count - Count records

Mutations

  • createOne{Model} - Create single
  • createMany{Model} - Create multiple
  • updateOne{Model} - Update single
  • updateMany{Model} - Update multiple
  • upsertOne{Model} - Create or update
  • deleteOne{Model} - Delete single
  • deleteMany{Model} - Delete multiple

Requirements

  • Node.js >= 18
  • Prisma >= 7.0
  • NestJS >= 10
  • @nestjs/graphql >= 12

License

MIT