0
0
NestJSframework~30 mins

Subscriptions in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Building a GraphQL Subscription with NestJS
📖 Scenario: You are creating a real-time chat application using NestJS and GraphQL. You want users to receive new messages instantly without refreshing the page.
🎯 Goal: Build a GraphQL subscription in NestJS that streams new chat messages to subscribed clients in real time.
📋 What You'll Learn
Create a simple message array to hold chat messages
Add a configuration variable for the subscription event name
Implement a subscription resolver using NestJS GraphQL decorators
Complete the subscription setup to broadcast new messages
💡 Why This Matters
🌍 Real World
Real-time chat apps, live notifications, and instant updates use subscriptions to push data to clients without refreshing.
💼 Career
Understanding subscriptions in NestJS is key for backend developers building interactive, real-time web applications.
Progress0 / 4 steps
1
Create the initial message data array
Create a constant array called messages with these exact objects: { id: 1, text: 'Hello' } and { id: 2, text: 'Welcome' }.
NestJS
Need a hint?

Use const messages = [ ... ] with two objects inside the array.

2
Add a subscription event name constant
Add a constant string called NEW_MESSAGE_EVENT and set it to 'newMessage'.
NestJS
Need a hint?

Use const NEW_MESSAGE_EVENT = 'newMessage'; to define the event name.

3
Implement the subscription resolver method
Inside a NestJS resolver class, create a method called newMessage decorated with @Subscription(() => Message) that returns an async iterator from pubSub.asyncIterator(NEW_MESSAGE_EVENT). Use pubSub as the PubSub instance.
NestJS
Need a hint?

Use @Subscription(() => Message) above the newMessage method and return pubSub.asyncIterator(NEW_MESSAGE_EVENT).

4
Complete the subscription by publishing new messages
Add a method called sendMessage that takes a text string, creates a new message object with an id one higher than the last message, pushes it to messages, and calls pubSub.publish(NEW_MESSAGE_EVENT, { newMessage: newMsg }).
NestJS
Need a hint?

Create sendMessage that adds a new message and publishes it with pubSub.publish.