0
0
NestJSframework~20 mins

Subscriptions in NestJS - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Subscription Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What does this NestJS subscription resolver output?

Consider this NestJS GraphQL subscription resolver snippet. What will the client receive when the triggerEvent method is called?

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

const pubSub = new PubSub();

@Resolver()
export class EventResolver {
  @Subscription(() => String, {
    filter: (payload, variables) => payload.event === variables.eventName,
  })
  eventTriggered(@Args('eventName') eventName: string) {
    return pubSub.asyncIterator('eventTriggered');
  }

  @Mutation(() => Boolean)
  async triggerEvent(@Args('event') event: string) {
    await pubSub.publish('eventTriggered', { event: event });
    return true;
  }
}
AThe client receives the event string only if the event name matches the subscription argument.
BThe client receives all events regardless of the event name argument.
CThe client receives an error because asyncIterator is used incorrectly.
DThe client receives no events because the filter function is incorrect.
Attempts:
2 left
💡 Hint

Look at the filter function inside the subscription decorator.

lifecycle
intermediate
2:00remaining
When is the subscription resolver's asyncIterator created in NestJS?

In a NestJS GraphQL subscription resolver, when is the asyncIterator function called during the subscription lifecycle?

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

const pubSub = new PubSub();

@Resolver()
export class SampleResolver {
  @Subscription(() => String)
  sampleSub() {
    return pubSub.asyncIterator('sampleEvent');
  }
}
AWhen the client sends a mutation, not during subscription.
BWhen the client first subscribes, creating a new async iterator for that client.
COnly when an event is published, triggering the async iterator.
DWhen the server starts, creating a single async iterator for all clients.
Attempts:
2 left
💡 Hint

Think about how subscriptions work per client connection.

🔧 Debug
advanced
2:00remaining
Why does this NestJS subscription never send events to clients?

Examine this subscription resolver code. Why do clients never receive events?

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

const pubSub = new PubSub();

@Resolver()
export class DebugResolver {
  @Subscription(() => String)
  messageSent() {
    return pubSub.asyncIterator('messageSent');
  }

  @Mutation(() => Boolean)
  sendMessage(@Args('msg') msg: string) {
    pubSub.publish('messageSent', { messageSent: msg });
    return true;
  }
}
AThe PubSub instance is not imported correctly, causing silent failures.
BThe mutation does not await pubSub.publish, causing race conditions.
CThe subscription resolver is missing the @Args decorator for the subscription argument.
DThe subscription returns asyncIterator for 'messageSent' but publishes with a payload key 'message' instead of 'messageSent'.
Attempts:
2 left
💡 Hint

Check the event name and payload keys used in publish and asyncIterator.

📝 Syntax
advanced
2:00remaining
Which option correctly defines a NestJS subscription with a filter?

Choose the correct syntax for a NestJS GraphQL subscription resolver that filters events by a variable userId.

A
@Subscription(() => String, { filter: (payload, variables) => variables.userId === payload.userId })
userMessages(userId: string) {
  return pubSub.asyncIterator('userMessages');
}
B
@Subscription(() => String, { filter: (payload) => payload.userId === userId })
userMessages(@Args('userId') userId: string) {
  return pubSub.asyncIterator('userMessages');
}
C
@Subscription(() => String, { filter: (payload, variables) => payload.userId === variables.userId })
userMessages(@Args('userId') userId: string) {
  return pubSub.asyncIterator('userMessages');
}
D
@Subscription(() => String, { filter: (payload, variables) => payload.userId == variables.userId })
userMessages(@Args('userId') userId: string) {
  return pubSub.asyncIterator('userMessages');
}
Attempts:
2 left
💡 Hint

Remember the filter function receives payload and variables as arguments.

state_output
expert
3:00remaining
What is the output sequence for this NestJS subscription with multiple publishes?

Given this NestJS subscription and mutation, what sequence of messages will a subscribed client receive after calling sendMessages?

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

const pubSub = new PubSub();

@Resolver()
export class SequenceResolver {
  @Subscription(() => String)
  messageStream() {
    return pubSub.asyncIterator('messageStream');
  }

  @Mutation(() => Boolean)
  async sendMessages() {
    await pubSub.publish('messageStream', { messageStream: 'First' });
    await pubSub.publish('messageStream', { messageStream: 'Second' });
    await pubSub.publish('messageStream', { messageStream: 'Third' });
    return true;
  }
}
AThe client receives messages in order: 'First', 'Second', 'Third'.
BThe client receives messages in reverse order: 'Third', 'Second', 'First'.
CThe client receives only the last message: 'Third'.
DThe client receives no messages because multiple publishes are not supported.
Attempts:
2 left
💡 Hint

Consider how PubSub handles multiple publishes and async iterators.