Performance: Subscriptions
Subscriptions impact the real-time data flow and responsiveness of the application, affecting interaction speed and server-client communication efficiency.
import { Resolver, Subscription, Args } from '@nestjs/graphql'; import { PubSub } from 'graphql-subscriptions'; const pubSub = new PubSub(); @Resolver() export class MessageResolver { @Subscription(() => String, { filter: (payload, variables) => payload.channelId === variables.channelId, }) messageAdded(@Args('channelId') channelId: string) { return pubSub.asyncIterator('messageAdded'); } }
import { Resolver, Subscription } from '@nestjs/graphql'; import { PubSub } from 'graphql-subscriptions'; const pubSub = new PubSub(); @Resolver() export class MessageResolver { @Subscription(() => String) messageAdded() { return pubSub.asyncIterator('messageAdded'); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Unfiltered global subscription | N/A | 0 | Minimal paint but high JS and network load | [X] Bad |
| Filtered subscription with args | N/A | 0 | Minimal paint and reduced JS/network load | [OK] Good |
@Subscription decorator marks a method as a GraphQL subscription resolver in NestJS.@Query is for queries, @Mutation for mutations, and @Injectable for services, not subscriptions.import { Resolver, Subscription } from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';
const pubSub = new PubSub();
@Resolver()
export class ChatResolver {
@Subscription(() => String, {
resolve: (payload) => `New message: ${payload.text}`,
})
messageAdded() {
return pubSub.asyncIterator('messageAdded');
}
}
// Somewhere else: pubSub.publish('messageAdded', { text: 'Hello!' });import { Resolver, Subscription } from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';
const pubSub = new PubSub();
@Resolver()
export class NotificationResolver {
@Subscription(() => String)
newNotification() {
return pubSub.asyncIterator('newNotification');
}
}
// Missing pubSub.publish call elsewherepubSub.publish('newNotification', ...) means no events are emitted, so clients receive no updates.pubSub.asyncIterator('messageAdded') directly without filtering.
B) Use the filter option in the @Subscription decorator to compare payload author and user ID.
C) Filter messages inside the resolver method after returning the async iterator.
D) Use a separate query instead of subscription to filter messages.filter option in the @Subscription decorator to send events selectively based on payload and context.filter option in the @Subscription decorator compares the message author with the client's user ID from context, sending only relevant updates. Subscribing directly without filtering sends all events to clients, filtering after the asyncIterator returns is not the standard approach, and using a query provides no live updates.Pass the test and this pattern moves unknown