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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@notiz/prisma-graphql-generator

v0.0.10

Published

Prisma Graphql Generator

Downloads

1

Readme

NestJS GraphQL Prisma Generator

Prisma generator to create NestJS types and CRUD resolvers based on your Prisma schema.

Installation

npm i -D @notiz/prisma-graphql-generator

Prisma

npm i -D prisma
npm i @prisma/client

# or with schematics
nest add nestjs-prisma

Additional dependencies

GraphQL Scalars for JSON, BigInt and Byte.

npm i graphql-scalars

Supporting aggregate and group by queries.

npm i graphql-fields
npm i -D @types/graphql-fields

Development

npm install

# setup postgres db
npm run docker:db
npm run migrate:dev


# build and run generator
npm run dev

# start nest dev server
npm run nest:dev

# open playground
open http://localhost:3000/graphql

Peer Dependencies

  "@nestjs/graphql": ">=7",
  "@prisma/client": "~2.29.1",
  "@types/graphql-fields": "*",
  "@types/node": "*",
  "class-transformer": "*",
  "graphql-scalars": "*",
  "graphql-fields": "*"

Configuration

Once installed the next step is to add a generator to your schema.prisma then run prisma generate.

generator nestjs {
  provider    = "prisma-nestjs"
  defaultTake = 20
}

The generator supports several options, above we are using defaultTake adjust the default value of items to return from findMany calls. Here is the full list of options currently supported.

| Key | Default Value | Description | | -------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | output | "node_modules/@generated/prisma/nestjs" | Where the generated resolvers should be emitted | | defaultTake | 20 | Adjust the default number returned from findMany() | | emitDMMF | false | Wether or not dmmf.json and prisma-client-dmmf.json should be emitted to the output directory for debugging | | emitTranspiled | false (true if output is includes node_modules) | Wether or not to emit as JavaScript rather then TypeScript |

Usage

Basic usage

Once the library is configured run prisma generate via the @prisma/cli package and your NestJS resolvers will be generated to the output folder.

prisma generate

From here you can add the resolves to any module's providers and the GraphQLModule will pick up on them.

import { UserCrudResolver } from '@generated/prisma/nestjs';

@Module({
  providers: [UserCrudResolver],
})
export class UserModule {}

Lastly you will need to add prisma (an instance of PrismaClient) to your GraphQL context in your GraphQLModule configuration

import { PrismaClient } from '@prisma/client';

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: true,
      context: { prisma: new PrismaClient() },
    }),
    UserModule,
  ],
})
export class AppModule {}

Now you are all set! You can now use whichever resolvers you provided in your GraphQL Queries.

Relations

In addition to the Crud Resolvers this generator generates Relation resolvers that use @ResolverField() to expose relations to the GraphQL Schema. You can simply import one of these generated relation resolvers and provide in a module.

import { UserRelationsResolver } from '@generated/prisma/nestjs';

@Module({
  providers: [UserRelationsResolver],
})
export class UserModule {}

Advanced usage

Custom operations

If you need to add your own logic (for example guards) to the generated resolvers you can either build your resolvers using the generated classes or extend from an existing resolver.

Using generated classes

import { User } from '@generated/prisma/nestjs';
import { GraphQLContext } from './some-interface-describing-context';

@Resolver(() => User)
export class CustomUserResolver {
  @Query(() => User)
  public async bestUser(@Context() { prisma }: GraphQLContext) {
    return prisma.user.findOne({ where: { username: 'menma' } });
  }

  @Mutation(() => User)
  public async randomUser(@Context() { prisma }: GraphQLContext) {
    const randomUser = faker.createCard();
    return prisma.user.create(randomUser);
  }
}

Extending an existing resolver

import { FindManyUserResolver } from '@generated/prisma/nestjs';
import { GraphQLContext } from './some-interface-describing-context';

@Resolver(() => User)
export class GuardedFindManyResolver {
  @Query(() => User)
  @UseGuard(SomeGuard)
  public async users(@Context() { prisma }: GraphQLContext) {
    return super.users({ prisma });
  }
}

Adding fields to model

Resolvers can be extended by adding @ResolverField() methods. This can be done in a completely new resolver and used along side the generated resolver.

For example:

@Resolver(() => User)
export class CustomUserResolver {
  @ResolverField(() => Post, { nullable: true })
  public async favoritePost(
    @Root() user: User,
    @Context() { prisma }: GraphQLContext
  ) {
    const [favoritePost] = await prisma.user
      .findOne({ where: { id: user.id } })
      .posts({ first: 1 });

    return favoritePost;
  }
}

Exposing selected Prisma actions

The generator generates many resolvers that allow you to pick and choose what operations you want to expose. For example if your model was User the following resolvers would be generated

| Action | Resolver | | ---------------------- | ---------------------- | | FindUnique | FindUniqueUserResolver | | FindFirst | FindFirstUserResolver | | FindMany | FindManyUserResolver | | Create | CreateUserResolver | | CreateMany | CreateManyUserResolver | | Update | UpdateUserResolver | | UpdateMany | UpdateManyUserResolver | | Delete | DeleteUserResolver | | DeleteMany | DeleteManyUserResolver | | Upsert | UpsertUserResolver | | Aggregate | AggregateUserResolver | | GroupBy | GroupByUserResolver | | Full CRUD (everything) | UserCrudResolver |

An example of picking FindMany, Create, Aggregate would look like so

@Module({
  providers: [FindManyUserResolver, CreateUserResolver, AggregateUserResolver],
})
export class UserModule {}

Exposing documentation

You can expose documentation directly to your GraphQL Schema by adding a comment with three slashes above a field or model.

/// A basic user account
model User {
 id     Int     @default(autoincrement()) @id

 /// Full email address, must be unique
 email  String  @unique

 /// Posts that the user has created
 posts  Post[]
}

Hiding model fields

Add doc line @NestJS.hide(output: true, input: false) to hide the field from output and/or input.

model User {
 id     Int     @default(autoincrement()) @id
 email  String  @unique
 /// @NestJS.hide(output: true)
 password String
}

Changing exposed model type name

You can change the exposed model name exposed in the GraphQL Schema by adding a doc line with @@NestJS.type above the model

/// @@NestJS.type(name: "Client")
model User {
  id     Int     @default(autoincrement()) @id
  email  String  @unique
  posts  Post[]
}

Changing exposed model type field name

Similarly you can rename exposed fields in your GraphQL Schema.

model User {
  id     Int     @default(autoincrement()) @id
  /// @NestJS.field(name: "emailAddress")
  email  String  @unique
  posts  Post[]
}

Note that Custom Resolvers will require you to transform the plain JSON prisma exports to the class generated prior to returning it as the renaming magic all occurs in the class.

const users = prisma.user.findMany();
return plainToClass(User, users);

All generated CRUD and relations resolvers fully support this feature and they map under the hood the original prisma property to the renamed field exposed in schema.

Complexity

Currently relation level complexity is supported. In order to use it you will need to have the complexity plugin setup with the fieldExtensionsEstimator() estimator as detailed in the NestJS Docs.

Complexity is calculated by adding the skip and take arguments then multiplying them by each field. Keep in mind that skip still requires prisma to read those rows thus is included in complexity calculations.

Example

{
  # Ignored until Query/Mutation level complexity support is added
  users(take: 100) {
    name

    # 80(take) + 20(skip) = 100(rows)
    # 100(rows) * ( 2(basic fields) + 20(nested relations) )
    # total: 2200
    posts(take: 80, skip: 20) {
      id
      body

      # 20(default take) + 0(skip) = 20(rows)
      # 20(rows) * 1(basic fields)
      # total: 20
      categories {
        name
      }
    }
  }
}
# total: 2200