Bird
Raised Fist0
NestJSframework~20 mins

Subscriptions in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of subscriptions in NestJS GraphQL?
easy
A. To perform database migrations
B. To send live updates automatically to clients
C. To handle HTTP GET requests
D. To serve static files

Solution

  1. Step 1: Understand the role of subscriptions

    Subscriptions are designed to push live data updates to clients without the client needing to request repeatedly.
  2. Step 2: Compare with other options

    HTTP GET requests, database migrations, and serving static files are unrelated to live data updates.
  3. Final Answer:

    To send live updates automatically to clients -> Option B
  4. Quick Check:

    Subscriptions = live updates [OK]
Hint: Subscriptions push live data updates automatically [OK]
Common Mistakes:
  • Confusing subscriptions with HTTP request handling
  • Thinking subscriptions manage database tasks
  • Assuming subscriptions serve static content
2. Which decorator is used in NestJS to define a GraphQL subscription method?
easy
A. @Query
B. @Mutation
C. @Subscription
D. @Injectable

Solution

  1. Step 1: Identify the decorator for subscriptions

    The @Subscription decorator marks a method as a GraphQL subscription resolver in NestJS.
  2. Step 2: Differentiate from other decorators

    @Query is for queries, @Mutation for mutations, and @Injectable for services, not subscriptions.
  3. Final Answer:

    @Subscription -> Option C
  4. Quick Check:

    @Subscription decorator = subscriptions [OK]
Hint: Use @Subscription decorator for live data methods [OK]
Common Mistakes:
  • Using @Query or @Mutation instead of @Subscription
  • Confusing @Injectable with subscription decorators
  • Omitting the decorator entirely
3. Given this subscription resolver snippet, what will be the output when a new message is published?
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!' });
medium
A. New message: Hello!
B. Hello!
C. messageAdded
D. Error: asyncIterator not found

Solution

  1. Step 1: Understand the subscription resolver

    The resolver listens to 'messageAdded' events and uses the resolve function to format the payload text.
  2. Step 2: Analyze the published payload

    The payload has { text: 'Hello!' }, so the resolve function returns 'New message: Hello!'.
  3. Final Answer:

    New message: Hello! -> Option A
  4. Quick Check:

    Resolve formats payload = 'New message: Hello!' [OK]
Hint: Resolve function formats payload text in subscription [OK]
Common Mistakes:
  • Expecting raw payload without resolve formatting
  • Confusing event name with output
  • Assuming asyncIterator causes error
4. Identify the error in this subscription setup:
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 elsewhere
medium
A. pubSub.asyncIterator called with wrong event name
B. Subscription method missing return statement
C. Incorrect decorator used for subscription
D. No events are published, so no updates sent

Solution

  1. Step 1: Check subscription method correctness

    The method correctly returns pubSub.asyncIterator with the event name.
  2. Step 2: Identify missing event publishing

    No call to pubSub.publish('newNotification', ...) means no events are emitted, so clients receive no updates.
  3. Final Answer:

    No events are published, so no updates sent -> Option D
  4. Quick Check:

    Missing publish call = no updates sent [OK]
Hint: Always publish events to trigger subscription updates [OK]
Common Mistakes:
  • Forgetting to call pubSub.publish
  • Using wrong event name in asyncIterator
  • Omitting return in subscription method
5. You want to create a subscription that only sends updates to clients when the message's author matches their user ID. Which approach correctly implements this filter in NestJS subscriptions? A) Use 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.
hard
A. Use filter option in @Subscription to send only matching messages
B. Subscribe directly without filtering; client filters messages
C. Filter messages inside resolver after asyncIterator returns
D. Use query instead of subscription for filtering

Solution

  1. Step 1: Understand subscription filtering

    NestJS supports a filter option in the @Subscription decorator to send events selectively based on payload and context.
  2. Step 2: Evaluate options

    The 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.
  3. Final Answer:

    Use filter option in @Subscription to send only matching messages -> Option A
  4. Quick Check:

    Filter option = selective subscription updates [OK]
Hint: Use @Subscription filter option to send selective updates [OK]
Common Mistakes:
  • Not using filter option and sending all events
  • Trying to filter after asyncIterator returns
  • Using queries instead of subscriptions for live updates
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard