All Projects → MichalLytek → typegraphql-nestjs

MichalLytek / typegraphql-nestjs

Licence: MIT license
TypeGraphQL integration with NestJS

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to typegraphql-nestjs

Firstsight
前后端分离,服务端渲染的个人博客,基于 Nodejs、 Vue、 Nuxt、Nestjs、PostgreSQL、Apollo
Stars: ✭ 19 (-83.76%)
Mutual labels:  nest, nestjs, type-graphql
aws-nestjs-starter
Serverless, AWS, NestJS, GraphQL and DynamoDB starter
Stars: ✭ 200 (+70.94%)
Mutual labels:  nest, nestjs, type-graphql
ogma
A monorepo for the ogma logger and related packages
Stars: ✭ 201 (+71.79%)
Mutual labels:  nest, nestjs
Notadd
A microservice development architecture based on nest.js. —— 基于 Nest.js 的微服务开发架构。
Stars: ✭ 2,556 (+2084.62%)
Mutual labels:  nest, nestjs
nestjs-starter
🚀 Nest framework starter
Stars: ✭ 30 (-74.36%)
Mutual labels:  nest, nestjs
nestjs-asyncapi
NestJS AsyncAPI module - generate the documentation of your event-based services using decorators
Stars: ✭ 88 (-24.79%)
Mutual labels:  nest, nestjs
Stator
Stator, your go-to template for the perfect stack. 😍🙏
Stars: ✭ 217 (+85.47%)
Mutual labels:  nest, nestjs
MyAPI
A template to create awesome APIs easily ⚡️
Stars: ✭ 117 (+0%)
Mutual labels:  nest, nestjs
Crud
NestJs CRUD for RESTful APIs
Stars: ✭ 2,709 (+2215.38%)
Mutual labels:  nest, nestjs
bundled-nest
💥 Nest 🔰 Webpack 🔰 Docker 💥 --- 🏯 Now archived for historical reference ⛩
Stars: ✭ 59 (-49.57%)
Mutual labels:  nest, nestjs
twitch-project
A weekly stream in which I build a web application with Neo4j and Typescript
Stars: ✭ 78 (-33.33%)
Mutual labels:  nest, nestjs
nest-queue
Queue manager for NestJS Framework for Redis (via bull package)
Stars: ✭ 69 (-41.03%)
Mutual labels:  nest, nestjs
Passport
Passport module for Nest framework (node.js) 🔑
Stars: ✭ 211 (+80.34%)
Mutual labels:  nest, nestjs
Mongoose
Mongoose module for Nest framework (node.js) 🍸
Stars: ✭ 191 (+63.25%)
Mutual labels:  nest, nestjs
Nestjs Typegoose
Typegoose with NestJS
Stars: ✭ 215 (+83.76%)
Mutual labels:  nest, nestjs
Cool Admin Api
cool-admin-api 是基于egg.js、typeorm、jwt等封装的api开发脚手架、快速开发api接口
Stars: ✭ 188 (+60.68%)
Mutual labels:  nest, nestjs
Jwt
JWT utilities module based on the jsonwebtoken package 🔓
Stars: ✭ 232 (+98.29%)
Mutual labels:  nest, nestjs
nestjs-telegraf
🤖 Powerful Nest module for easy and fast creation Telegram bots
Stars: ✭ 300 (+156.41%)
Mutual labels:  nest, nestjs
Config
Configuration module for Nest framework (node.js) 🍓
Stars: ✭ 161 (+37.61%)
Mutual labels:  nest, nestjs
Elasticsearch
Elasticsearch module based on the official elasticsearch package 🌿
Stars: ✭ 176 (+50.43%)
Mutual labels:  nest, nestjs

typegraphql logo nest logo

TypeGraphQL NestJS Module

Basic integration of TypeGraphQL in NestJS.

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

Installation

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

npm i typegraphql-nestjs @nestjs/graphql

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

npm i type-graphql

How to use?

The typegraphql-nestjs package exports TypeGraphQLModule dynamic module, which is based on the official NestJS GraphQLModule. It exposes three static methods:

.forRoot()

The first one is TypeGraphQLModule.forRoot() which you should call on your root module, just like with the official GraphQLModule.

The only difference is that as its argument you can provide typical TypeGraphQL buildSchema options like emitSchemaFile or authChecker apart from the standard GqlModuleOptions from @nestjs/graphql like installSubscriptionHandlers or context:

import { Module } from "@nestjs/common";
import { TypeGraphQLModule } from "typegraphql-nestjs";

import RecipeModule from "./recipe/module";
import { authChecker } from "./auth";

@Module({
  imports: [
    TypeGraphQLModule.forRoot({
      emitSchemaFile: true,
      validate: false,
      authChecker,
      dateScalarMode: "timestamp",
      context: ({ req }) => ({ currentUser: req.user }),
    }),
    RecipeModule,
  ],
})
export default class AppModule {}

Then, inside the imported modules (like RecipeModule) you just need to register the resolvers classes in the module providers array:

import { Module } from "@nestjs/common";

import RecipeResolver from "./resolver";
import RecipeService from "./service";

@Module({
  providers: [RecipeResolver, RecipeService],
})
export default class RecipeModule {}

And that's it! 😁

Notice that the resolvers classes are automatically inferred from your submodules providers array, so you don't need to specify resolvers property from TypeGraphQL buildSchema options inside TypeGraphQLModule.forRoot().

.forFeature()

In case of need to provide orphanedTypes setting, you should use TypeGraphQLModule.forFeature(). The recommended place for that is in the module where the orphaned type (like SuperRecipe) belongs:

import { Module } from "@nestjs/common";
import { TypeGraphQLModule } from "typegraphql-nestjs";

import RecipeResolver from "./resolver";
import RecipeService from "./service";
import { SuperRecipe } from "./types";

@Module({
  imports: [
    TypeGraphQLModule.forFeature({
      orphanedTypes: [SuperRecipe],
    }),
  ],
  providers: [RecipeResolver, RecipeService],
})
export default class RecipeModule {}

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

.forRootAsync()

If you need to access some services to construct the TypeGraphQLModule options, you might be interested in the TypeGraphQLModule.forRootAsync() method. It allows you to define your own useFactory implementation where you have injected services from imports option.

Example of using the config service to generate TypeGraphQLModule options:

@Module({
  imports: [
    ConfigModule,
    RecipeModule,
    TypeGraphQLModule.forRootAsync({
      inject: [ConfigService],
      useFactory: async (config: ConfigService) => ({
        cors: true,
        debug: config.isDevelopmentMode,
        playground: !config.isDevelopmentMode,
        validate: false,
        dateScalarMode: "timestamp",
        emitSchemaFile:
          config.isDevelopmentMode && path.resolve(__dirname, "schema.gql"),
      }),
    }),
  ],
})
export default class AppModule {}

TypeGraphQLFederationModule

typegraphql-nestjs has also support for Apollo Federation.

However, Apollo Federation requires building a federated GraphQL schema, hence you need to use the TypeGraphQLFederationModule module, designed specially for that case.

The usage is really similar to the basic TypeGraphQLModule - the only different is that .forFeature() method has an option to provide referenceResolvers object which is needed in some cases of Apollo Federation:

function resolveUserReference(
  reference: Pick<User, "id">,
): Promise<User | undefined> {
  return db.users.find({ id: reference.id });
}

@Module({
  imports: [
    TypeGraphQLFederationModule.forFeature({
      orphanedTypes: [User],
      referenceResolvers: {
        User: {
          __resolveReference: resolveUserReference,
        },
      },
    }),
  ],
  providers: [AccountsResolver],
})
export default class AccountModule {}

The .forRoot() method has no differences but you should provide the skipCheck: true option as federated schema can violate the standard GraphQL schema rules like at least one query defined:

@Module({
  imports: [
    TypeGraphQLFederationModule.forRoot({
      validate: false,
      skipCheck: true,
    }),
    AccountModule,
  ],
})
export default class AppModule {}

Be aware that you cannot mix TypeGraphQLFederationModule.forRoot() with the base TypeGraphQLModule.forFeature() one. You need to consistently use only TypeGraphQLFederationModule across all modules.

Then, for exposing the federated schema using Apollo Gateway, you should use the standard NestJS GraphQLGatewayModule.

Caveats

While this integration provides a way to use TypeGraphQL with NestJS modules and dependency injector, for now it doesn't support other 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, with typegraphql-nestjs you can also take advantage of additional features (comparing to @nestjs/graphql) like inline field resolvers, Prisma 2 integration or up-to-date capabilities like deprecating input fields and args (thanks to always synced with latests graphql-js).

Examples

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

  1. Basics

    Basics of the integration, like TypeGraphQLModule.forRoot usage

  2. Multiple Servers

    Advanced usage of multiple schemas inside single NestJS app - demonstration of schema isolation in modules and TypeGraphQLModule.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. Apollo Federation

    Showcase of Apollo Federation approach, using the TypeGraphQLFederationModule and GraphQLGatewayModule.

  5. Middlewares

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

You can run them by using ts-node, like npx ts-node ./examples/1-basics/index.ts.

All examples folders contain a query.gql file with some examples operations you can perform on the GraphQL servers.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].