So far, in this series, we’ve used GraphQL both to fetch and modify data. While this covers many real-life cases, modern applications often include situations in which users need immediate feedback when some event occurs.
One of the solutions suggested by the GraphQL team is polling. In this technique, the client periodically requests the API for changes. It is a straightforward approach and works out of the box without much code. Unfortunately, usually, updates can be unpredictable. Therefore, polling is often wasteful and introduces unnecessary traffic in our API.
To counter the above issue, with GraphQL, we have a concept of subscriptions. They act as a way for the clients to listen for events in real-time. The client informs the server that it cares about a set of events. When they trigger, the server is responsible for notifying the client. To achieve that, the server needs to declare the events that the client can listen to.
Under the hood, an active connection between the client and the server establishes. Thanks to that, we can push messages from the server to our users. Usually, subscriptions in GraphQL are implemented with WebSockets, although the official specification does not enforce that. There were some attempts in implementing subscriptions using Server-sent events, for example.
If you want to know how to use NestJS with WebSockets, check out API with NestJS #26. Real-time chat with WebSockets
Implementing subscriptions with NestJS
The very first step in implementing subscriptions is enabling them. To do so, we need to turn on the installSubscriptionHandlers property.
1import { Module } from '@nestjs/common';
2import { ConfigModule, ConfigService } from '@nestjs/config';
3import { GraphQLModule } from '@nestjs/graphql';
4import { join } from 'path';
5
6@Module({
7 imports: [
8 GraphQLModule.forRootAsync({
9 imports: [ConfigModule],
10 inject: [ConfigService],
11 useFactory: (
12 configService: ConfigService,
13 ) => ({
14 playground: Boolean(configService.get('GRAPHQL_PLAYGROUND')),
15 autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
16 installSubscriptionHandlers: true
17 })
18 }),
19 // ...
20 ],
21 controllers: [],
22 providers: [],
23})
24export class AppModule {}Creating an instance of a PubSub
The first concept that we need to grasp is the PubSub. Its job is to be a middleman between the logic of our application and the GraphQL subscriptions engine. It does that by exposing a simple publish and subscribe API.
Under the hood, NestJS uses Apollo, which is a widespread GraphQL implementation. A part of the Apollo architecture is the graphql-subscriptions library. It does contain a ready-to-use PubSub. Unfortunately, it is not meant to be used in production, though, as mentioned in the docs. It wouldn’t work with multiple instances of our NestJS server. Also, it does not scale beyond a few connections.
Among the suggested PubSub implementations, the most popular seems to be the graphql-redis-subscriptions library.
We’ve already used Redis in this series in API with NestJS #24. Cache with Redis. Running the app in a Node.js cluster. If you want to know how to set up Redis with docker, check it out.
When initializing a PubSub, let’s take the advice from Jay McDoniel, one of the NestJS library maintainers. It includes defining a global module with an instance of the PubSub.
1import { ConfigModule, ConfigService } from '@nestjs/config';
2import { RedisPubSub } from 'graphql-redis-subscriptions';
3import { Global, Module } from '@nestjs/common';
4
5export const PUB_SUB = 'PUB_SUB';
6
7@Global()
8@Module({
9 imports: [ConfigModule],
10 providers: [
11 {
12 provide: PUB_SUB,
13 useFactory: (
14 configService: ConfigService
15 ) => new RedisPubSub({
16 connection: {
17 host: configService.get('REDIS_HOST'),
18 port: configService.get('REDIS_PORT'),
19 }
20 }),
21 inject: [ConfigService]
22 }
23 ],
24 exports: [PUB_SUB],
25})
26export class PubSubModule {}Global modules should be registered only once, preferably in the AppModule, our root module. Doing so makes them available everywhere.
Defining the subscription
In the twenty-seventh part of this series, we’ve defined the model of a post. This article aims to define a subscription that allows our users to listen to newly-created posts.
To define a subscription using the code-first approach, we need to use the @Subscription() decorator.
1import { Resolver, Subscription } from '@nestjs/graphql';
2import { Post } from './models/post.model';
3import PostsService from './posts.service';
4import { Inject } from '@nestjs/common';
5import { RedisPubSub } from 'graphql-redis-subscriptions';
6import { PUB_SUB } from '../pubSub/pubSub.module';
7
8const POST_ADDED_EVENT = 'postAdded';
9
10@Resolver(() => Post)
11export class PostsResolver {
12 constructor(
13 private postsService: PostsService,
14 @Inject(PUB_SUB) private pubSub: RedisPubSub
15 ) {}
16
17 @Subscription(() => Post)
18 postAdded() {
19 return this.pubSub.asyncIterator(POST_ADDED_EVENT);
20 }
21
22 // ...
23}Please note that the name of the event matches the postAdded method. If that’s not the case, we need to pass additional options to the @Subscription() decorator.
Above, we return the AsyncIterator every time a client requests a subscription. Thanks to that, every time we call pubSub.publish(POST_ADDED_EVENT), the clients who subscribed will receive the event.
1import { Args, Context, Mutation, Resolver } from '@nestjs/graphql';
2import { Post } from './models/post.model';
3import PostsService from './posts.service';
4import { CreatePostInput } from './inputs/post.input';
5import { Inject, UseGuards } from '@nestjs/common';
6import RequestWithUser from '../authentication/requestWithUser.interface';
7import { GraphqlJwtAuthGuard } from '../authentication/graphql-jwt-auth.guard';
8import { RedisPubSub } from 'graphql-redis-subscriptions';
9import { PUB_SUB } from '../pubSub/pubSub.module';
10
11const POST_ADDED_EVENT = 'postAdded';
12
13@Resolver(() => Post)
14export class PostsResolver {
15 constructor(
16 private postsService: PostsService,
17 @Inject(PUB_SUB) private pubSub: RedisPubSub
18 ) {}
19
20 @Mutation(() => Post)
21 @UseGuards(GraphqlJwtAuthGuard)
22 async createPost(
23 @Args('input') createPostInput: CreatePostInput,
24 @Context() context: { req: RequestWithUser },
25 ) {
26 const newPost = await this.postsService.createPost(createPostInput, context.req.user);
27 this.pubSub.publish(POST_ADDED_EVENT, { postAdded: newPost });
28 return newPost;
29 }
30
31 // ...
32}Thanks to doing that, our clients can subscribe to incoming posts. We can try that through the GraphQL playground:
Above, we can see that the subscription is active, and the client listens to incoming events. When the post gets created, it is visible in the interface right away.
Filtering events
We can pass additional options to the @Subscribe() decorator. One of them is the filter function. It has the payload and the variables as its arguments. If it returns false, the event is filtered out and not returned to the clients.
1@Subscription(() => Post, {
2 filter: (payload, variables) => {
3 return payload.postAdded.title === 'Hello world!';
4 }
5})
6postAdded() {
7 return this.pubSub.asyncIterator(POST_ADDED_EVENT);
8}Modifying the payload before sending
Another optional option of the @Subscribe() decorator is the resolve function. It can modify the payload before sending it to the client.
1@Subscription(() => Post, {
2 resolve: (value) => {
3 return {
4 ...value.postAdded,
5 title: `Title: ${value.postAdded.title}`
6 }
7 }
8})
9postAdded() {
10 return this.pubSub.asyncIterator(POST_ADDED_EVENT);
11}We can also access injected providers both in the resolve and filter functions. To do that, use the following:
1@Subscription(() => Post, {
2 filter: function (this: PostsResolver, payload, variables) {
3 const postsService = this.postsService;
4 return true;
5 },
6 resolve: function (this: PostsResolver, value) {
7 const postsService = this.postsService;
8 return {
9 ...value.postAdded,
10 title: `Title: ${value.postAdded.title}`
11 }
12 }
13})
14postAdded() {
15 return this.pubSub.asyncIterator(POST_ADDED_EVENT);
16}Summary
In this article, we’ve looked into how we can update our users with our application’s newest state. Although one of the solutions might be polling, it has its drawbacks. Therefore, we’ve implemented subscriptions that under the hood use WebSockets. Combined with the Redis-based PubSub, we can send events to our users in a performant way.