Nestjs graphql-redis-subscriptions

Author : JaNakh Pon , September 04, 2021

Tags

Summary

In this article, we are going to use subscriptions with redis by simply installing the dependency graphql-redis-subscriptions to the repo from the previous article.


Installation & Schema

Firstly, let's install the required dependency and add a new module for redis pubsub 😉:

  > npm i graphql-redis-subscriptions --save
  > cd src && nest g module pubsub && cd ..

And add configuration to "pubsub.module.ts"

pubsub.module.ts
import { Global, Module } from '@nestjs/common';
import { RedisPubSub } from 'graphql-redis-subscriptions';

export const PUB_SUB = 'PUB_SUB';
@Global()
@Module({
  imports: [],
  providers: [
    {
      provide: PUB_SUB,
      useFactory: () =>
        new RedisPubSub({
          connection: {
            host: 'localhost',
            port: '6379',
          },
        }),
    },
  ],
  exports: [PUB_SUB],
})
export class PubsubModule {}

And now, let's use "RedisPubSub" in todo.resolver.ts instead of "PubSub" from 'graphql-subscriptions':

todo.resolver.ts
import { UseGuards, Inject } from '@nestjs/common';
import { RedisPubSub } from 'graphql-redis-subscriptions';
import { PUB_SUB } from '../../pubsub/pubsub.module';

@Resolver('Todo')
export class TodoResolver {
    constructor(
        private todoService: TodoService,
        @Inject(PUB_SUB) private pubSub: RedisPubSub,
    ) { }
    .
    .
    .
}

Now, we can go to localhost:3001/graphql and play with subscriptions in Graphql Playground! 😉.

Source Code.