Subscriptions

In addition to fetching data using queries and modifying data using mutations, the GraphQL spec supports a third operation type, called subscription. GraphQL subscriptions are a way to push data from the server to the clients that choose to listen to real time messages from the server. Subscriptions are similar to queries in that they specify a set of fields to be delivered to the client, but instead of immediately returning a single answer, a channel is opened and a result is sent to the client every time a particular event happens on the server.

A common use case for subscriptions is notifying the client side about particular events, for example the creation of a new object, updated fields and so on (read more here).

Enable subscriptions

To enable subscriptions, set the installSubscriptionHandlers property to true.

  1. GraphQLModule.forRoot({
  2. installSubscriptionHandlers: true,
  3. }),

Code first

To create a subscription using the code first approach, we use the @Subscription() decorator and the PubSub class from the graphql-subscriptions package, which provides a simple publish/subscribe API.

The following subscription handler takes care of subscribing to an event by calling PubSub#asyncIterator. This method takes a single argument, the triggerName, which corresponds to an event topic name.

  1. const pubSub = new PubSub();
  2. @Resolver(of => Author)
  3. export class AuthorResolver {
  4. // ...
  5. @Subscription(returns => Comment)
  6. commentAdded() {
  7. return pubSub.asyncIterator('commentAdded');
  8. }
  9. }

Hint All decorators are exported from the @nestjs/graphql package, while the PubSub class is exported from the graphql-subscriptions package.

NotePubSub is a class that exposes a simple publish and subscribe API. Read more about it here. Note that the Apollo docs warn that the default implementation is not suitable for production (read more here). Production apps should use a PubSub implementation backed by an external store (read more here).

This will result in generating the following part of the GraphQL schema in SDL:

  1. type Subscription {
  2. commentAdded(): Comment!
  3. }

Note that subscriptions, by definition, return an object with a single top level property whose key is the name of the subscription. This name is either inherited from the name of the subscription handler method (i.e., commentAdded above), or is provided explicitly by passing an option with the key name as the second argument to the @Subscription() decorator, as shown below.

  1. @Subscription(returns => Comment, {
  2. name: 'commentAdded',
  3. })
  4. addCommentHandler() {
  5. return pubSub.asyncIterator('commentAdded');
  6. }

This construct produces the same SDL as the previous code sample, but allows us to decouple the method name from the subscription.

Publishing

Now, to publish the event, we use the PubSub#publish method. This is often used within a mutation to trigger a client-side update when a part of the object graph has changed. For example:

posts/posts.resolver.ts

  1. @Mutation(returns => Post)
  2. async addComment(
  3. @Args('postId', { type: () => Int }) postId: number,
  4. @Args('comment', { type: () => Comment }) comment: CommentInput,
  5. ) {
  6. const newComment = this.commentsService.addComment({ id: postId, comment });
  7. pubSub.publish('commentAdded', { commentAdded: newComment });
  8. return newComment;
  9. }

The PubSub#publish method takes a triggerName (again, think of this as an event topic name) as the first parameter, and an event payload as the second parameter. As mentioned, the subscription, by definition, returns a value and that value has a shape. Look again at the generated SDL for our commentAdded subscription:

  1. type Subscription {
  2. commentAdded(): Comment!
  3. }

This tells us that the subscription must return an object with a top-level property name of commentAdded that has a value which is a Comment object. The important point to note is that the shape of the event payload emitted by the PubSub#publish method must correspond to the shape of the value expected to return from the subscription. So, in our example above, the pubSub.publish('commentAdded', { commentAdded: newComment }) statement publishes a commentAdded event with the appropriately shaped payload. If these shapes don’t match, your subscription will fail during the GraphQL validation phase.

Filtering subscriptions

To filter out specific events, set the filter property to a filter function. This function acts similar to the function passed to an array filter. It takes two arguments: payload containing the event payload (as sent by the event publisher), and variables taking any arguments passed in during the subscription request. It returns a boolean determining whether this event should be published to client listeners.

  1. @Subscription(returns => Comment, {
  2. filter: (payload, variables) =>
  3. payload.commentAdded.title === variables.title,
  4. })
  5. commentAdded(@Args('title') title: string) {
  6. return pubSub.asyncIterator('commentAdded');
  7. }

Mutating subscription payloads

To mutate the published event payload, set the resolve property to a function. The function receives the event payload (as sent by the event publisher) and returns the appropriate value.

  1. @Subscription(returns => Comment, {
  2. resolve: value => value,
  3. })
  4. commentAdded() {
  5. return pubSub.asyncIterator('commentAdded');
  6. }

Note If you use the resolve option, you should return the unwrapped payload (e.g., with our example, return a newComment object directly, not a { commentAdded: newComment } object).

If you need to access injected providers (e.g., use an external service to validate the data), use the following construction.

  1. @Subscription(returns => Comment, {
  2. resolve(this: AuthorResolver, value) {
  3. // "this" refers to an instance of "AuthorResolver"
  4. return value;
  5. }
  6. })
  7. commentAdded() {
  8. return pubSub.asyncIterator('commentAdded');
  9. }

The same construction works with filters:

  1. @Subscription(returns => Comment, {
  2. filter(this: AuthorResolver, payload, variables) {
  3. // "this" refers to an instance of "AuthorResolver"
  4. return payload.commentAdded.title === variables.title;
  5. }
  6. })
  7. commentAdded() {
  8. return pubSub.asyncIterator('commentAdded');
  9. }

Schema first

To create an equivalent subscription in Nest, we’ll make use of the @Subscription() decorator.

  1. const pubSub = new PubSub();
  2. @Resolver('Author')
  3. export class AuthorResolver {
  4. // ...
  5. @Subscription()
  6. commentAdded() {
  7. return pubSub.asyncIterator('commentAdded');
  8. }
  9. }

To filter out specific events based on context and arguments, set the filter property.

  1. @Subscription('commentAdded', {
  2. filter: (payload, variables) =>
  3. payload.commentAdded.title === variables.title,
  4. })
  5. commentAdded() {
  6. return pubSub.asyncIterator('commentAdded');
  7. }

To mutate the published payload, we can use a resolve function.

  1. @Subscription('commentAdded', {
  2. resolve: value => value,
  3. })
  4. commentAdded() {
  5. return pubSub.asyncIterator('commentAdded');
  6. }

If you need to access injected providers (e.g., use an external service to validate the data), use the following construction:

  1. @Subscription('commentAdded', {
  2. resolve(this: AuthorResolver, value) {
  3. // "this" refers to an instance of "AuthorResolver"
  4. return value;
  5. }
  6. })
  7. commentAdded() {
  8. return pubSub.asyncIterator('commentAdded');
  9. }

The same construction works with filters:

  1. @Subscription('commentAdded', {
  2. filter(this: AuthorResolver, payload, variables) {
  3. // "this" refers to an instance of "AuthorResolver"
  4. return payload.commentAdded.title === variables.title;
  5. }
  6. })
  7. commentAdded() {
  8. return pubSub.asyncIterator('commentAdded');
  9. }

The last step is to update the type definitions file.

  1. type Author {
  2. id: Int!
  3. firstName: String
  4. lastName: String
  5. posts: [Post]
  6. }
  7. type Post {
  8. id: Int!
  9. title: String
  10. votes: Int
  11. }
  12. type Query {
  13. author(id: Int!): Author
  14. }
  15. type Comment {
  16. id: String
  17. content: String
  18. }
  19. type Subscription {
  20. commentAdded(title: String!): Comment
  21. }

With this, we’ve created a single commentAdded(title: String!): Comment subscription. You can find a full sample implementation here.

PubSub

We instantiated a local PubSub instance above. The preferred approach is to define PubSub as a provider and inject it through the constructor (using the @Inject() decorator). This allows us to re-use the instance across the whole application. For example, define a provider as follows, then inject 'PUB_SUB' where needed.

  1. {
  2. provide: 'PUB_SUB',
  3. useValue: new PubSub(),
  4. }

Customize subscriptions server

To customize the subscriptions server (e.g., change the listener port), use the subscriptions options property (read more).

  1. GraphQLModule.forRoot({
  2. installSubscriptionHandlers: true,
  3. subscriptions: {
  4. keepAlive: 5000,
  5. }
  6. }),