Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

TypeGraphQL integration with NestJS

License

NotificationsYou must be signed in to change notification settings

MichalLytek/typegraphql-nestjs

Repository files navigation

typegraphql logonest logo

TypeGraphQL NestJS Module

Basic integration ofTypeGraphQL inNestJS.

Allows to use TypeGraphQL features while integrating with NestJS modules system and dependency injector.

Installation

First, you need to instal thetypegraphql-nestjs module along with@nestjs/graphql:

npm i typegraphql-nestjs @nestjs/graphql

If you haven't installed it yet, it's time to addtype-graphql into the project:

npm i type-graphql

How to use?

Thetypegraphql-nestjs package exportsTypeGraphQLModule dynamic module, which is based on the official NestJSGraphQLModule. It exposes three static methods:

.forRoot()

The first one isTypeGraphQLModule.forRoot() which you should call on your root module, just like with the officialGraphQLModule.

The only difference is that as its argument you can providetypical TypeGraphQLbuildSchema options likeemitSchemaFile orauthChecker apart from thestandardGqlModuleOptions from@nestjs/graphql likeinstallSubscriptionHandlers orcontext:

import{Module}from"@nestjs/common";import{TypeGraphQLModule}from"typegraphql-nestjs";importRecipeModulefrom"./recipe/module";import{authChecker}from"./auth";@Module({imports:[TypeGraphQLModule.forRoot({driver:ApolloDriver,emitSchemaFile:true,      authChecker,scalarsMap:[{type:Date,scalar:GraphQLTimestamp}],context:({ req})=>({currentUser:req.user}),}),RecipeModule,],})exportdefaultclassAppModule{}

Then, inside the imported modules (likeRecipeModule) you just need to register the resolvers classes in the moduleproviders array:

import{Module}from"@nestjs/common";importRecipeResolverfrom"./resolver";importRecipeServicefrom"./service";@Module({providers:[RecipeResolver,RecipeService],})exportdefaultclassRecipeModule{}

And that's it! 😁

Notice that the resolvers classes are automatically inferred from your submodulesproviders array, so you don't need to specifyresolvers property from TypeGraphQLbuildSchema options insideTypeGraphQLModule.forRoot().

.forFeature()

In case of need to provideorphanedTypes setting, you should useTypeGraphQLModule.forFeature(). The recommended place for that is in the module where the orphaned type (likeSuperRecipe) belongs:

import{Module}from"@nestjs/common";import{TypeGraphQLModule}from"typegraphql-nestjs";importRecipeResolverfrom"./resolver";importRecipeServicefrom"./service";import{SuperRecipe}from"./types";@Module({imports:[TypeGraphQLModule.forFeature({orphanedTypes:[SuperRecipe],}),],providers:[RecipeResolver,RecipeService],})exportdefaultclassRecipeModule{}

Using.forFeature() ensures proper schemas isolation and automatically supplyorphanedTypes option for underlyingbuildSchema from TypeGraphQL - again, there's no need to provide it manually in.forRoot() options.

.forRootAsync()

If you need to access some services to construct theTypeGraphQLModule options, you might be interested in theTypeGraphQLModule.forRootAsync() method. It allows you to define your ownuseFactory implementation where you have injected services fromimports option.

Example of using the config service to generateTypeGraphQLModule options:

@Module({imports:[ConfigModule,RecipeModule,TypeGraphQLModule.forRootAsync({driver:ApolloDriver,inject:[ConfigService],useFactory:async(config:ConfigService)=>({cors:true,debug:config.isDevelopmentMode,playground:!config.isDevelopmentMode,scalarsMap:[{type:Date,scalar:GraphQLTimestamp}],emitSchemaFile:config.isDevelopmentMode&&path.resolve(__dirname,"schema.graphql"),}),}),],})exportdefaultclassAppModule{}

Apollo Federation

typegraphql-nestjs has also support forApollo Federation.

However, Apollo Federation requires building a federated GraphQL schema, hence you need to adjust your code a bit.

The usage is really similar to the basic case - the only difference is that inTypeGraphQLModule.forFeature() method you can provide areferenceResolvers option object, which is needed in some cases of Apollo Federation:

functionresolveUserReference(reference:Pick<User,"id">,):Promise<User|undefined>{returndb.users.find({id:reference.id});}@Module({imports:[TypeGraphQLModule.forFeature({orphanedTypes:[User],referenceResolvers:{User:{__resolveReference:resolveUserReference,},},}),],providers:[AccountsResolver],})exportdefaultclassAccountModule{}

For the.forRoot() method there's no differences - just need to providedriver: ApolloFederationDriver option in order to build a subgraph schema, same as withGraphQLModule from@nestjs/graphql described in theNestJS docs. However, you also need to explicitly setup federation version, by usingfederationVersion option:

@Module({imports:[TypeGraphQLModule.forRoot({driver:ApolloFederationDriver,federationVersion:2,}),AccountModule,],})exportdefaultclassAppModule{}

Then, for exposing the federated schema using Apollo Gateway, you should use the standardNestJSApolloGatewayDriver solution.

Caveats

While this integration provides a way to use TypeGraphQL with NestJS modules and dependency injector, for now it doesn't supportother NestJS features like guards, interceptors, filters and pipes.

To achieve the same goals, you can use standard TypeGraphQL equivalents - middlewares, custom decorators, built-in authorization and validation.

Moreover, withtypegraphql-nestjs you can also take advantage of additional features (comparing to@nestjs/graphql) likeinline field resolvers,Prisma 2 integration or up-to-date capabilities like deprecating input fields and args (thanks to always synced with latestsgraphql-js).

Examples

You can see some examples of the integration in this repo:

  1. Basics

    Basics of the integration, likeTypeGraphQLModule.forRoot usage

  2. Multiple Servers

    Advanced usage of multiple schemas inside single NestJS app - demonstration of schema isolation in modules andTypeGraphQLModule.forFeature usage

  3. Request scoped dependencies

    Usage of request scoped dependencies - retrieving fresh instances of resolver and service classes on every request (query/mutation)

  4. Middlewares

    Usage of class-based middlewares - modules, providers and schema options

  5. Apollo Federation (OLD)

    Showcase of the legacy Apollo Federation approach

  6. Apollo Federation V2

    Showcase of the new Apollo Federation V2 approach

Most of them you can run by usingts-node, likenpx ts-node ./examples/1-basics/index.ts.

All examples folders contain aquery.graphql file with some examples operations you can perform on the GraphQL servers.

Security contact information

To report a security vulnerability, please use theTidelift security contact.Tidelift will coordinate the fix and disclosure.

About

TypeGraphQL integration with NestJS

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors4

  •  
  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp