0
0
NestJSframework~5 mins

Subscriptions in NestJS

Choose your learning style9 modes available
Introduction

Subscriptions let your app send real-time updates to users. They keep users informed without needing to refresh the page.

You want to show live chat messages as they arrive.
You need to update a dashboard with live data like stock prices.
You want to notify users instantly when new content is available.
You want to build a live feed or notifications system.
You want to push updates to clients without them asking repeatedly.
Syntax
NestJS
import { Resolver, Subscription } from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';

const pubSub = new PubSub();

@Resolver()
export class MyResolver {
  @Subscription(() => String, {
    resolve: (payload) => payload,
  })
  messageSent() {
    return pubSub.asyncIterator('messageSent');
  }
}

Use @Subscription decorator to mark a method as a subscription.

PubSub helps send and listen to events for subscriptions.

Examples
This example listens for 'newMessage' events and sends the string message to subscribers.
NestJS
import { Resolver, Subscription } from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';

const pubSub = new PubSub();

@Resolver()
export class ChatResolver {
  @Subscription(() => String)
  newMessage() {
    return pubSub.asyncIterator('newMessage');
  }
}
This example filters notifications so only the user with matching userId receives them.
NestJS
import { Resolver, Subscription } from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';

const pubSub = new PubSub();

@Resolver()
export class NotificationResolver {
  @Subscription(() => String, {
    filter: (payload, variables) => payload.userId === variables.userId,
  })
  userNotification(userId: string) {
    return pubSub.asyncIterator('userNotification');
  }
}
Sample Program

This resolver stores messages and allows clients to send new messages via mutation. When a message is sent, it publishes an event. The subscription listens for these events and sends new messages to subscribers in real-time.

NestJS
import { Resolver, Subscription, Query, Mutation, Args } from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';

const pubSub = new PubSub();

@Resolver()
export class MessageResolver {
  private messages: string[] = [];

  @Query(() => [String])
  getMessages() {
    return this.messages;
  }

  @Mutation(() => Boolean)
  sendMessage(@Args('message') message: string) {
    this.messages.push(message);
    pubSub.publish('messageSent', message);
    return true;
  }

  @Subscription(() => String)
  messageSent() {
    return pubSub.asyncIterator('messageSent');
  }
}
OutputSuccess
Important Notes

Subscriptions require a WebSocket connection to work properly.

Use PubSub or other event systems to manage events.

Remember to handle cleanup to avoid memory leaks in long-running subscriptions.

Summary

Subscriptions let your app send live updates to users.

Use @Subscription decorator and PubSub to create subscriptions.

They are great for chat, notifications, and live data feeds.