Complete the code to import the required module for GraphQL subscriptions in NestJS.
import { [1] } from '@nestjs/graphql';
The GraphQLModule is imported from @nestjs/graphql to enable GraphQL features including subscriptions.
Complete the code to define a subscription method in a NestJS resolver.
@Subscription() [1]() { return pubSub.asyncIterator('messageAdded'); }
The @Subscription() decorator marks subscription resolver methods. The method returns pubSub.asyncIterator('messageAdded'). Conventionally, the method is named subscribe.
Fix the error in the subscription setup by completing the missing import.
import { PubSub } from '[1]'; const pubSub = new PubSub();
The PubSub class used for subscriptions comes from the graphql-subscriptions package, which provides a simple event pub-sub mechanism.
Fill both blanks to correctly configure the GraphQLModule for subscriptions in NestJS.
GraphQLModule.forRoot({
installSubscriptionHandlers: [1],
subscriptions: {
'graphql-ws': [2]
}
})To enable subscriptions, installSubscriptionHandlers must be set to true. The subscriptions option can be configured with an empty object {} to use default settings for 'graphql-ws'.
Fill all three blanks to create a subscription resolver that publishes a message event.
import { Resolver, [1] } from '@nestjs/graphql'; import { PubSub } from 'graphql-subscriptions'; const pubSub = new PubSub(); @Resolver() export class MessageResolver { @[2]() messageAdded() { return pubSub.asyncIterator('messageAdded'); } async addMessage(content: string) { await pubSub.[3]('messageAdded', { messageAdded: content }); } }
The Subscription decorator marks the subscription method. The publish method of pubSub sends events to subscribers.