• Stars
    star
    502
  • Rank 84,862 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 4 years ago
  • Updated 23 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generate object types, inputs, args, etc. from prisma schema file for usage with @nestjs/graphql module

prisma-nestjs-graphql

Generate object types, inputs, args, etc. from prisma schema file for usage with @nestjs/graphql module.

Features

  • Generates only necessary imports
  • Combines zoo of nested/nullable filters
  • Does not generate resolvers, since it's application specific

Install

npm install --save-dev prisma-nestjs-graphql

Usage

  1. Add new generator section to schema.prisma file
generator nestgraphql {
    provider = "node node_modules/prisma-nestjs-graphql"
    // for yarn monorepos
    // provider = "prisma-nestjs-graphql"
    output = "../src/@generated"
}
  1. Run prisma generate
npx prisma generate
  1. If your models have Decimal and Json types, you need install:
npm install graphql-type-json prisma-graphql-type-decimal

Or write you own graphql scalar types, read more on docs.nestjs.com.

Generator options

output

Output folder relative to this schema file
Type: string

outputFilePattern

File path and name pattern
Type: string
Default: {model}/{name}.{type}.ts
Possible tokens:

  • {model} Model name in dashed case or 'prisma' if unknown
  • {name} Dashed-case name of model/input/arg without suffix
  • {type} Short type name (model, input, args, output)
  • {plural.type} Plural short type name (models, inputs, enums)

tsConfigFilePath

Path to tsconfig.json (absolute path or relative to current working directory)
Type: string | undefined
Default: tsconfig.json if exists, undefined otherwise

combineScalarFilters

Combine nested/nullable scalar filters to single
Type: boolean
Default: false

noAtomicOperations

Remove input types for atomic operations
Type: boolean
Default: false

reExport

Create index.ts file with re-export
Type: enum
Values:
None Default, create nothing
Directories Create index file in all root directories
Single Create single index file in output directory
All Create index file in all root directories and in output directory

Example configuration:

generator nestgraphql {
    provider = "node node_modules/prisma-nestjs-graphql"
    output = "../src/@generated"
    reExport = Directories
}

emitSingle

Generate single file with merged classes and enums.
Type: boolean
Default: false

emitCompiled

Emit compiled JavaScript and definitions instead of TypeScript sources, files will be compiled with emitDecoratorMetadata:false, because there is a problem with temporal dead zone when generating merged file.
Type: boolean
Default: false

purgeOutput

Delete all files in output folder
Type: boolean
Default: false

noTypeId

Disable usage of graphql ID type and use Int/Float for fields marked as @id in schema.
Type: boolean
Default: false

requireSingleFieldsInWhereUniqueInput

When a model *WhereUniqueInput class has only a single field, mark that field as required (TypeScript) and not nullable (GraphQL).
See #58 for more details.
Type: boolean
Default: false
Note: It will break compatiblity between Prisma types and generated classes.

useInputType

Since GraphQL does not support input union type, this setting map allow to choose which input type is preferable.

generator nestgraphql {
    useInputType_{typeName}_{property} = "{pattern}"
}

Where:

  • typeName Full name or partial name of the class where need to choose input type.
    Example: UserCreateInput full name, WhereInput partial name, matches UserWhereInput, PostWhereInput, etc.
  • property Property of the class for which need to choose type. Special case name ALL means any / all properties.
  • pattern Part of name (or full) of type which should be chosen, you can use wild card or negate symbols, in this case pattern should starts with match:, e.g. match:*UncheckedCreateInput see outmatch for details.

Example:

export type PostWhereInput = {
  author?: XOR<UserRelationFilter, UserWhereInput>;
};
export type UserRelationFilter = {
  is?: UserWhereInput;
  isNot?: UserWhereInput;
};

export type UserWhereInput = {
  AND?: Enumerable<UserWhereInput>;
  OR?: Enumerable<UserWhereInput>;
  NOT?: Enumerable<UserWhereInput>;
  id?: StringFilter | string;
  name?: StringFilter | string;
};

We have generated types above, by default property author will be decorated as UserRelationFilter, to set UserWhereInput need to configure generator the following way:

generator nestgraphql {
  provider = "node node_modules/prisma-nestjs-graphql"
  output = "../src/@generated"
  useInputType_WhereInput_ALL = "WhereInput"
}
@InputType()
export class PostWhereInput {
  @Field(() => UserWhereInput, { nullable: true })
  author?: UserWhereInput;
}

decorate

Allow to attach multiple decorators to any field of any type.

generator nestgraphql {
    decorate_{key}_type = "outmatch pattern"
    decorate_{key}_field = "outmatch pattern"
    decorate_{key}_from = "module specifier"
    decorate_{key}_name = "import name"
    decorate_{key}_arguments = "[argument1, argument2]"
    decorate_{key}_defaultImport = "default import name" | true
    decorate_{key}_namespaceImport = "namespace import name"
    decorate_{key}_namedImport = "import name" | true
}

Where {key} any identifier to group values (written in flatten style)

  • decorate_{key}_type - outmatch pattern to match class name
  • decorate_{key}_field - outmatch pattern to match field name
  • decorate_{key}_from - module specifier to import from (e.g class-validator)
  • decorate_{key}_name - import name or name with namespace
  • decorate_{key}_defaultImport - import as default
  • decorate_{key}_namespaceImport - use this name as import namespace
  • decorate_{key}_namedImport - named import (without namespace)
  • decorate_{key}_arguments - arguments for decorator (if decorator need to be called as function)
    Special tokens can be used:
    • {propertyType.0} - field's type (TypeScript type annotation)

Example of generated class:

@ArgsType()
export class CreateOneUserArgs {
  @Field(() => UserCreateInput, { nullable: false })
  data!: UserCreateInput;
}

To make it validateable (assuming UserCreateInput already contains validation decorators from class-validator), it is necessary to add @ValidateNested() and @Type() from class-transformer.

decorate_1_type = "CreateOneUserArgs"
decorate_1_field = data
decorate_1_name = ValidateNested
decorate_1_from = "class-validator"
decorate_1_arguments = "[]"
decorate_2_type = "CreateOneUserArgs"
decorate_2_field = data
decorate_2_from = "class-transformer"
decorate_2_arguments = "['() => {propertyType.0}']"
decorate_2_name = Type

Result:

import { ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';

@ArgsType()
export class CreateOneUserArgs {
  @Field(() => UserCreateInput, { nullable: false })
  @ValidateNested()
  @Type(() => UserCreateInput)
  data!: UserCreateInput;
}

Another example:

decorate_2_namespaceImport = "Transform"
decorate_2_name = "Transform.Type"
import * as Transform from 'class-transformer';

@Transform.Type(() => UserCreateInput)
data!: UserCreateInput;

Add @HideField() decorator to nested types:

decorate_3_type = "*CreateNestedOneWithoutUserInput"
decorate_3_field = "!(create)"
decorate_3_name = "HideField"
decorate_3_from = "@nestjs/graphql"
decorate_3_arguments = "[]"

May generate following class:

@Field(() => ProfileCreateWithoutUserInput, { nullable: true })
create?: ProfileCreateWithoutUserInput;

@HideField()
connectOrCreate?: ProfileCreateOrConnectWithoutUserInput;

@HideField()
connect?: ProfileWhereUniqueInput;

graphqlScalars

Allow to set custom graphql type for Prisma scalar type. Format:

graphqlScalars_{type}_name = "string"
graphqlScalars_{type}_specifier = "string"

where {type} is a prisma scalar type name (e.g. BigInt)

Example:

graphqlScalars_BigInt_name = "GraphQLBigInt"
graphqlScalars_BigInt_specifier = "graphql-scalars"

May generate:

import { GraphQLBigInt } from 'graphql-scalars';

export class BigIntFilter {
  @Field(() => GraphQLBigInt, { nullable: true })
  equals?: bigint | number;
}

It will affect all inputs and outputs types (including models).

Documentation and field options

Comments with triple slash will projected to typescript code comments and some @Field() decorator options

For example:

model Product {
  /// Old description
  /// @deprecated Use new name instead
  oldName String
}

May produce:

@ObjectType()
export class Product {
  /**
   * Old description
   * @deprecated Use new name instead
   */
  @Field(() => String, {
    description: 'Old description',
    deprecationReason: 'Use new name instead',
  })
  oldName: string;
}

Field Settings

Special directives in triple slash comments for more precise code generation.

@HideField()

Removes field from GraphQL schema.
Alias: @TypeGraphQL.omit(output: true)

By default (without arguments) field will be decorated for hide only in output types (type in schema).
To hide field in input types add input: true.
To hide field in specific type you can use glob pattern match: string | string[] see outmatch for details.

Examples:

  • @HideField() same as @HideField({ output: true })
  • @HideField({ input: true, output: true })
  • @HideField({ match: 'UserCreate*Input' })
model User {
    id String @id @default(cuid())
    /// @HideField()
    password String
    /// @HideField({ output: true, input: true })
    secret String
    /// @HideField({ match: '@(User|Comment)Create*Input' })
    createdAt DateTime @default(now())
}

May generate classes:

@ObjectType()
export class User {
  @HideField()
  password: string;
  @HideField()
  secret: string;
  @Field(() => Date, { nullable: false })
  createdAt: Date;
}
@InputType()
export class UserCreateInput {
  @Field()
  password: string;
  @HideField()
  secret: string;
  @HideField()
  createdAt: Date;
}

Custom Decorators

Applying custom decorators requires configuration of generator.

generator nestgraphql {
    fields_{namespace}_from = "module specifier"
    fields_{namespace}_input = true | false
    fields_{namespace}_output = true | false
    fields_{namespace}_model = true | false
    fields_{namespace}_defaultImport = "default import name" | true
    fields_{namespace}_namespaceImport = "namespace import name"
    fields_{namespace}_namedImport = true | false
}

Create configuration map in flatten style for {namespace}.
Where {namespace} is a namespace used in field triple slash comment.

fields_{namespace}_from

Required. Name of the module, which will be used in import (class-validator, graphql-scalars, etc.)
Type: string

fields_{namespace}_input

Means that it will be applied on input types (classes decorated by InputType)
Type: boolean
Default: false

fields_{namespace}_output

Means that it will be applied on output types (classes decorated by ObjectType), including models
Type: boolean
Default: false

fields_{namespace}_model

Means that it will be applied only on model types (classes decorated by ObjectType)
Type: boolean
Default: false

fields_{namespace}_defaultImport

Default import name, if module have no namespace.
Type: undefined | string | true
Default: undefined
If defined as true then import name will be same as {namespace}

fields_{namespace}_namespaceImport

Import all as this namespace from module
Type: undefined | string
Default: Equals to {namespace}

fields_{namespace}_namedImport

If imported module has internal namespace, this allow to generate named import,
imported name will be equal to {namespace}, see example of usage
Type: boolean
Default: false

Custom decorators example:

generator nestgraphql {
    fields_Validator_from = "class-validator"
    fields_Validator_input = true
}

model User {
    id Int @id
    /// @Validator.MinLength(3)
    name String
}

May generate following class:

import { InputType, Field } from '@nestjs/graphql';
import * as Validator from 'class-validator';

@InputType()
export class UserCreateInput {
  @Field(() => String, { nullable: false })
  @Validator.MinLength(3)
  name!: string;
}

Custom decorators can be applied on classes (models):

/// @NG.Directive('@extends')
/// @NG.Directive('@key(fields: "id")')
model User {
    /// @NG.Directive('@external')
    id String @id
}

generator nestgraphql {
    fields_NG_from = "@nestjs/graphql"
    fields_NG_output = false
    fields_NG_model = true
}

May generate:

import * as NG from '@nestjs/graphql';

@NG.Directive('@extends')
@NG.Directive('@key(fields: "id")')
export class User {
    @Field(() => ID, { nullable: false })
    @NG.Directive('@external')
    id!: string;

@FieldType()

Allow set custom GraphQL scalar type for field

To override scalar type in specific classes, you can use glob pattern match: string | string[] see outmatch for details.

model User {
    id Int @id
    /// @FieldType({ name: 'Scalars.GraphQLEmailAddress', from: 'graphql-scalars', input: true })
    email String
}

May generate following class:

import { InputType, Field } from '@nestjs/graphql';
import * as Scalars from 'graphql-scalars';

@InputType()
export class UserCreateInput {
  @Field(() => Scalars.GraphQLEmailAddress, { nullable: false })
  email!: string;
}

And following GraphQL schema:

scalar EmailAddress

input UserCreateInput {
    email: EmailAddress!
}

Same field type may be used in different models and it is not convenient to specify every time all options. There is a shortcut:

generator nestgraphql {
    fields_Scalars_from = "graphql-scalars"
    fields_Scalars_input = true
    fields_Scalars_output = true
}

model User {
    id Int @id
    /// @FieldType('Scalars.GraphQLEmailAddress')
    email String
}

The result will be the same. Scalars is the namespace here. Missing field options will merged from generator configuration.

@PropertyType()

Similar to @FieldType() but refer to TypeScript property (actually field too).

To override TypeScript type in specific classes, you can use glob pattern match: string | string[] see outmatch for details.

Example:

generator nestgraphql {
    fields_TF_from = "type-fest"
}

model User {
    id String @id
    /// @PropertyType('TF.JsonObject')
    data Json
}

May generate:

import * as TF from 'type-fest';

@ObjectType()
export class User {
  @Field(() => GraphQLJSON)
  data!: TF.JsonObject;
}

@Directive()

Allow attach @Directive decorator from @nestjs/graphql

GraphQL federation example:

/// @Directive({ arguments: ['@extends'] })
/// @Directive({ arguments: ['@key(fields: "id")'] })
model User {
    /// @Directive({ arguments: ['@external'] })
    id String @id
}

May generate:

@ObjectType()
@Directive('@extends')
@Directive('@key(fields: "id")')
export class User {
  @Field(() => ID, { nullable: false })
  @Directive('@external')
  id!: string;
}

@ObjectType()

Allow rename type in schema and mark as abstract.

Example 1:

// schema.prisma
/// @ObjectType({ isAbstract: true })
model User {
    id Int @id
}
@ObjectType({ isAbstract: true })
export class User {}

Example 2:

// schema.prisma
/// @ObjectType('Human', { isAbstract: true })
model User {
    id Int @id
}
@ObjectType('Human', { isAbstract: true })
export class User {}

Using lirary in other generators

import { generate } from 'prisma-nestjs-graphql/generate';

Similar Projects

Resources

More Repositories

1

tailwind-components

Collection of components found on the internet
TypeScript
1,813
star
2

solution-architecture

Solution Architecture links, articles, books, video lessons, etc.
627
star
3

sublime-import-helper

A Sublime Text Plugin that helps you to import your modules.
Python
68
star
4

postcss-import-url

PostCSS plugin inlines remote files.
JavaScript
48
star
5

eslint-plugin-nestjs

POC. ESLint rules for nestjs framework
TypeScript
38
star
6

gulp-cssimport

Parses a CSS file, finds imports, grabs the content of the linked file and replaces the import statement with it.
JavaScript
36
star
7

nest-vite-node-starter

Nest.JS via vite example
TypeScript
26
star
8

prisma-query-log

Log prisma query event
TypeScript
24
star
9

eslint-plugin-tsc

Wraps a TypeScript compiler checks
TypeScript
22
star
10

gulp-extract-media-queries

Plugin extracts css rules inside of media queries and saves it to separated files.
JavaScript
19
star
11

prisma-graphql-type-decimal

GraphQL type for Prisma's Decimal scalar, wrapper around decimal.js
TypeScript
17
star
12

react-typescript-realworld-example-app

React TypeScript realworld example app
TypeScript
12
star
13

node-package-starter

Node package starter
JavaScript
12
star
14

jest-createspyobj

Helper function to create spy object for `jest`, same as `jasmine.createSpyObj`
JavaScript
7
star
15

nightmare-xpath

Nightmare plugin to select nodes by xpath expression.
JavaScript
7
star
16

UsefulFunctions

Garden plugin. Useful functions for plugin and application developers (ex- PluginUtils).
PHP
5
star
17

awesome-stars

A curated list of my GitHub stars!
5
star
18

class-validator-flat-formatter

Convert array of ValidationError objects from class-validator to multiline string
TypeScript
4
star
19

eslint-plugin-ngxs-style-guide

ESLint rules for ngxs state manager
TypeScript
3
star
20

fusebox-gulp-plugin

Adapt gulp plugins to work with fuse-box
TypeScript
3
star
21

eslint-plugin-no-eslint-disable

Disallow disable rules by `eslint-disable` comment.
JavaScript
3
star
22

import-adjutor

Parse ecmascript modules and collect names of export vars, functions, etc.
TypeScript
3
star
23

PageSpeed

Garden plugin.
PHP
3
star
24

useful-functions

[DEPRECATED] Useful functions for everyday javascript
JavaScript
3
star
25

PinnedFooter

jQuery plugin. Footer always at the bottom of the page, not window.
JavaScript
3
star
26

bookmarks

A continuously expanded list of framework/libraries and tools I used/want to use when building things on the web. Mostly Javascript stuff.
3
star
27

nestjs-cqrx

EventStoreDB NestJS CQRS module
TypeScript
3
star
28

remark-package-dependencies

Inject to markdown the list of dependencies of your package
JavaScript
3
star
29

ngx-modal

Open modal window for your Angular X application
TypeScript
2
star
30

cp1251-utf8

Converts string from windows-1251 (cp1251) to unicode (utf8).
JavaScript
2
star
31

SilexSandbox

PHP
2
star
32

prisma-permissions-experiment

Prisma experiment - permissions stored in database
TypeScript
2
star
33

changed

Check if file was changed
TypeScript
2
star
34

monorepo-playground2

Monorepo playground 2: TypeScript, wireit
JavaScript
2
star
35

microfrontends-playground

Microfrontends links
2
star
36

onn

Event emitter using DOM's addEventListener/dispatchEvent
JavaScript
2
star
37

HelloNode

Test Sublime Text 3 plugin.
Python
2
star
38

parent-process-pid

Gets parent process id (PPID)
JavaScript
2
star
39

remark-sources

Inserts source code to markdown files
JavaScript
2
star
40

odata-query-sql

Converts odata query to sql query.
JavaScript
2
star
41

sublime-markdown-link

Convert url to markdown link where description is title from remote url
Python
2
star
42

inject

Inject a dependency (service locator pattern)
TypeScript
2
star
43

webhive

Web development news aggregator
TypeScript
2
star
44

nest-config

Deprecated in flavor of @nestjs-steroids/environment. Configuration module for Nest.js (wraps convict module).
TypeScript
2
star
45

requiro

Advanced version of require for node.js
JavaScript
2
star
46

Mvc

Mvc service for Silex.
PHP
2
star
47

tailwind-float-label

Tailwind plugin to add floating label, control with float label components
HTML
2
star
48

typescript-service

Language service which helps to get diagnostic messages from typescript source files.
TypeScript
2
star
49

ThankfulPeople

Vanilla II plugin.
PHP
1
star
50

tailwind-ie-variant

Tailwind CSS plugin to add variants (css hacks) for IE10+
JavaScript
1
star
51

nx-workspace

Create and develop Nx Workspace with nest preset
TypeScript
1
star
52

rv-home-ru-source

rv-home.ru sources
PHP
1
star
53

GridBox

Fluid grid system (using css3-boxsizing, fallback for IE<7)
CSS
1
star
54

express-json-rpc

JSON-RPC for Express.
JavaScript
1
star
55

esm-exports

Parse ES2015 modules
TypeScript
1
star
56

monorepo-playground3

Monorepo playground 3
TypeScript
1
star
57

how-to-create-eslint-plugin-talk

JavaScript
1
star
58

query-builder

TypeScript
1
star
59

mini-node-package-starter

Mini node package starter (ESM)
JavaScript
1
star
60

tailwind-playground

TypeScript
1
star
61

react-nx-workspace

Create and develop nx monorepository
TypeScript
1
star
62

nestolog

Logger for NestJS, implements `LoggerService`
TypeScript
1
star
63

wireit-package

Update wireit scripts across your workspace packages
TypeScript
1
star
64

inotifywait-win32

Windows binaries of thekid/inotify-win
1
star
65

Identicon5

Garden plugin. Identicon5 (jQuery).
JavaScript
1
star
66

inject-compile-time

Play with Custom Transformer for Typescript that enables compile-time Dependency Injection
TypeScript
1
star
67

example-backend-api

JavaScript
1
star
68

angular-webpack-seed

Angular 2 seed project - Webpack 2, TypeScript 2, Angular 4+, Karma / Nightmare 2, Stryker, Gulp 4, ESLint and more
TypeScript
1
star
69

babel-plugin-postcss

Replace import from css expression to lit-element's css tag function
TypeScript
1
star
70

graphql-starter

Trying to play with graphql and type-grapqhl
JavaScript
1
star
71

typescript-transform-unspec

Typescript transform plugin removes spec definition from source file
TypeScript
1
star
72

database-utils

Database utils for node.js.
JavaScript
1
star
73

nestjs-sqlmancer-realworld-example-app

WIP. NestJS & SqlMancer realworld example app
TypeScript
1
star
74

remark-plantuml-link

Generate a plantuml image link from text
TypeScript
1
star
75

api-koa-typescript-starter

TypeScript
1
star
76

react-typescript-vite-app

Scaffolding and developing `@vite/create-app --template template-react-ts`
TypeScript
1
star
77

mochapack-node-playground

Playing with mochapack
JavaScript
1
star
78

path-of-the-rust-web-developer

Follow https://github.com/csharad/rust-web-developer-roadmap
Rust
1
star
79

semantic-release-workspace-dependency

semantic-release plugin to update version of workspace dependency
TypeScript
1
star
80

PesenkaProBomzha

Song about vagperson with no fixed abode (git developing test repo).
1
star
81

moonrepo-example

TypeScript
1
star
82

gulpfile

JavaScript
1
star
83

git-ftp

PHP
1
star
84

VkAuth

Vkontakte authentication for Garden.
PHP
1
star
85

DtCss

Adapts DtCSS to work with Garden. DtCSS is a PHP script that preprocesses your CSS file. It speeds up CSS coding by extending the features to CSS. Such as nested selectors, color mixing and more. DtCSS reads the CSS file with special syntax written for DtCSS, and outputs the standard CSS.
PHP
1
star
86

you-dont-need-task-runner

How to manage your workflow in shell without task runner (gulp, grunt, fly, just, etc.)
Shell
1
star
87

thesaurus-service

Provides synonym for word, uses remote sites (words.bighugelabs.com, thesaurus.altervista.org, thesaurus.com, etc.)
JavaScript
1
star