All Projects → Davide-Gheri → nestjs-mercurius

Davide-Gheri / nestjs-mercurius

Licence: MIT license
NestJs module to use Mercurius as GraphQL server

Programming Languages

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

Projects that are alternatives of or similar to nestjs-mercurius

nestjs-throttler-storage-redis
Redis storage provider for the nestjs-throttler package.
Stars: ✭ 56 (+47.37%)
Mutual labels:  fastify, nestjs
Notadd
A microservice development architecture based on nest.js. —— 基于 Nest.js 的微服务开发架构。
Stars: ✭ 2,556 (+6626.32%)
Mutual labels:  fastify, nestjs
nestjs-api-mongoose
Collection example apps with NestJS and Typeorm, Sequelize, Mongodb, PostgreSQL, MySQL, GraphQL, Mercurius, etc. for the NestJS community 😻
Stars: ✭ 153 (+302.63%)
Mutual labels:  nestjs, mercurius
nest-rest-mongo-boilerplate
🍱 backend with nest (typescript), mongoose, and authentication
Stars: ✭ 180 (+373.68%)
Mutual labels:  fastify, nestjs
nodejs-integration-tests-best-practices
✅ Beyond the basics of Node.js testing. Including a super-comprehensive best practices list and an example app (April 2022)
Stars: ✭ 2,842 (+7378.95%)
Mutual labels:  fastify, nestjs
azure-func-http
Azure Functions HTTP adapter for Nest framework (node.js) 🌥
Stars: ✭ 121 (+218.42%)
Mutual labels:  nestjs
blog-be-next
The back-end platform for Yancey blog.
Stars: ✭ 33 (-13.16%)
Mutual labels:  nestjs
nestjs-extensions
[WIP] A bunch of useful and opinionated filters, modules, pipes... to use with Nest framework. 😻
Stars: ✭ 43 (+13.16%)
Mutual labels:  nestjs
starter-reactnative-nestjs-mysql
Starter mobile ReactNative NestJS MySQL with continuous integration and AWS deployment
Stars: ✭ 16 (-57.89%)
Mutual labels:  nestjs
nest-xray
Distributed tracing for Nestjs with AWS X-Ray as the backend. Instrument incoming and outgoing HTTP requests
Stars: ✭ 50 (+31.58%)
Mutual labels:  nestjs
truthy
Open source headless CMS API written using NestJS, that has pre built modules like User Management, Role Management, Permission Management, Email Module, Account Settings, OTP, Throttling, RBAC support, Localization, and many more.
Stars: ✭ 200 (+426.32%)
Mutual labels:  nestjs
zoia2 old
Zoia CMS
Stars: ✭ 24 (-36.84%)
Mutual labels:  fastify
fastify-nodemailer
Fastify nodemailer plugin
Stars: ✭ 23 (-39.47%)
Mutual labels:  fastify
graphql-utils
Utilities and helpers to make working with GraphQL.js based APIs simpler.
Stars: ✭ 42 (+10.53%)
Mutual labels:  nestjs
create-fastify
Rapidly generate a Fastify project
Stars: ✭ 56 (+47.37%)
Mutual labels:  fastify
unnue-nuxt
开媛笔记,基于nuxt ssr首屏服务器端渲染 ⚡。用于分享、记录、交流和学习,希望可以帮助到小伙伴们。同时网站在永久更新,备好鸡血,一起来战 Ooh aah!
Stars: ✭ 98 (+157.89%)
Mutual labels:  nestjs
nestjs-microservice-boilerplate
Boilerplate for a TCP Microservice in NestJS with TypeORM and tests
Stars: ✭ 45 (+18.42%)
Mutual labels:  nestjs
nestjs-dynamoose
Dynamoose module for Nest
Stars: ✭ 84 (+121.05%)
Mutual labels:  nestjs
matnbaz
📚 The source-code for matnbaz.net. A monorepo containing the back-end (NestJS/Prisma/Apollo), front-end (Next.js/Apollo) and some tooling.
Stars: ✭ 481 (+1165.79%)
Mutual labels:  nestjs
BUA-FE
本科毕设,搭建一套小而全面的校园外卖系统。主要使用wei-xin-mini + TypeScript + nest.js + typeORM + rabbitmq技术栈。
Stars: ✭ 20 (-47.37%)
Mutual labels:  nestjs

If you want to use Mercurius with @nestjs/graphql > v10, please use the @nestjs/mercurius package

Nestjs Mercurius

Use Mercurius GraphQL with Nestjs framework

Visit the Wiki

Install

npm i @nestjs/platform-fastify fastify mercurius nestjs-mercurius

Use

Register the module

import { Module } from '@nestjs/common';
import { MercuriusModule } from 'nestjs-mercurius';

@Module({
  imports: [
    // Work also with async configuration (MercuriusModule.forRootAsync)
    MercuriusModule.forRoot({
      autoSchemaFile: true,
      context: (request, reply) => ({
        user: request.user,
      }),
      subscription: {
        context: (connection, request) => ({
          user: request.user,
        }),
      },
    }),
  ],
  providers: [
    CatResolver,
  ],
})
export class AppModule {}

The Object type

import { Field, ID, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class Cat {
  @Field(() => ID)
  id: number;
  
  @Field()
  name: string;
  
  @Field(() => Int)
  ownerId: number;
}

The Resolver

import { Resolver, Query, ResolveField, Parent, Mutation, Subscription, Context, Args } from '@nestjs/graphql';
import { ParseIntPipe } from '@nestjs/common';
import { ResolveLoader, toAsyncIterator, LoaderQuery } from 'nestjs-mercurius';
import { PubSub } from 'mercurius';
import { Cat } from './cat';

@Resolver(() => Cat)
export class CatResolver {
  constructor(
    private readonly catService: CatService,
    private readonly userService: UserService,
  ) {}

  @Query(() => [Cat])
  cats(@Args({name: 'filter', type: () => String, nullable: true}) filter?: string) {
    return this.catService.find(filter);
  }

  @Query(() => Cat, { nullable: true })
  cat(@Args('id', ParseIntPipe) id: number) {
    return this.catService.findOne(id);
  }

  @Mutation(() => Cat)
  createCat(
    @Args('name') name: string,
    @Context('pubsub') pubSub: PubSub,
    @Context('user') user: User,
  ) {
    const cat = new Cat();
    cat.name = name;
    cat.ownerId = user.id;
    //...
    pubSub.publish({
      topic: 'CatCreated',
      payload: { cat },
    });
    return cat;
  }
  
  @Subscription(() => Cat, {
    resolve: (payload) => payload.cat,
    filter: (payload, vars, context) =>
      payload.cat.ownerId !== context.user.id,
  })
  onCatCreated(
    @Context('pubsub') pubSub: PubSub,
  ) {
    return toAsyncIterator(pubSub.subscribe('CatCreated'));
  }
  
  @ResolveField(() => Int)
  age(@Parent() cat: Cat) {
    return 5;
  }
  
  @ResolveLoader(() => User, { opts: { cache: false } })
  owner(
    @Parent() queries: LoaderQuery<Cat>[],
  ) {
    return this.userService.findById(
      // queries is an array of objects defined as { obj, params } where obj is the current object and params are the GraphQL params
      queries.map(({ obj }) => obj.ownerId)
    );
  }
}

Federation

Install necessary dependencies

npm i @apollo/federation

The Gateway

import { Module } from '@nestjs/common';
import { MercuriusGatewayModule } from 'nestjs-mercurius';

@Module({
  imports: [
    MercuriusGatewayModule.forRoot({
      graphiql: 'playground',
      subscription: true,
      gateway: {
        pollingInterval: 10000,
        services: [
          {
            name: 'users',
            url: 'https://....',
            wsUrl: 'wss://...',
          },
          {
            name: 'pets',
            url: 'https://...',
            rewriteHeaders: headers => headers,
          },
        ],
      },
    }),
  ],
})
export class GatewayModule {}

The Service

import { Module } from '@nestjs/common';
import { MercuriusModule } from './mercurius.module';
import { User } from './user';
import { PetResolver, UserResolver } from './resolvers';

@Module({
  imports: [
    MercuriusModule.forRoot({
      autoSchemaFile: true,
      federationMetadata: true,
      buildSchemaOptions: {
        orphanedTypes: [User],
      },
      //...
    }),
  ],
  providers: [
    PetResolver,
    UserResolver,
  ],
})
export class PetModule {}

The Resolver

import { Resolver, ResolveReference } from '@nestjs/graphql';
import { Pet } from './pet';
import { Reference } from './reference.interface';

@Resolver(() => Pet)
export class PetResolver {
  constructor(
    private readonly petService: PetService,
  ) {}

  @ResolveReference()
  resolveReference(ref: Reference<'Pet', 'id'>) {
    return this.petService.findOne(ref.id);
  }
}

Resolve reference could also be defined as Loader, potentially improving performance:

import { ResolveReferenceLoader } from './resolve-reference-loader.decorator';
import { LoaderQuery } from './loader.interface';

@Resolver(() => Pet)
export class PetResolver {
  constructor(
    private readonly petService: PetService,
  ) {}

  @ResolveReferenceLoader()
  resolveReference(refs: LoaderQuery<Reference<'Pet', 'id'>>) {
    return this.petService.findById(
      refs.map(({ obj }) => obj.id)
    );
  }
}

Hooks

Register mercurius hooks as service methods, using the @GraphQLHook() decorator

import { GraphQLHook } from 'nestjs-mercurius';

@Injectable()
export class HookService {
  @GraphQLHook('preValidation')
  async onPreValidation(schema: GraphQLSchema, source: DocumentNode, context: any) {
   //...
  }
}
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].