Bird
0
0

Given this code snippet, what will be the output on the second request to /hello?

medium📝 component behavior Q13 of 15
NestJS - Interceptors
Given this code snippet, what will be the output on the second request to /hello?
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor } from '@nestjs/cache-manager';

@Controller()
export class HelloController {
  private count = 0;

  @UseInterceptors(CacheInterceptor)
  @Get('hello')
  getHello() {
    this.count++;
    return `Hello count: ${this.count}`;
  }
}
A"Hello count: 1" first request, "Hello count: 2" second request
BError because count is private
C"Hello count: 0" on both requests
D"Hello count: 1" on first and second request
Step-by-Step Solution
Solution:
  1. Step 1: Understand CacheInterceptor behavior

    CacheInterceptor caches the response of the first request and returns it for subsequent requests without calling the method again.
  2. Step 2: Analyze the count variable increment

    On the first request, count increments to 1 and returns "Hello count: 1". On the second request, the cached response is returned, so count does not increment again.
  3. Final Answer:

    "Hello count: 1" on first and second request -> Option D
  4. Quick Check:

    Cache returns cached response = B [OK]
Quick Trick: CacheInterceptor returns cached response, method not re-executed [OK]
Common Mistakes:
  • Assuming count increments on every request
  • Thinking private variables cause errors here
  • Ignoring caching effect on method execution

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes