Bird
0
0

You want to measure the time taken by any request handler in your NestJS app. Which interceptor approach correctly adds this cross-cutting timing logic?

hard📝 Application Q15 of 15
NestJS - Interceptors
You want to measure the time taken by any request handler in your NestJS app. Which interceptor approach correctly adds this cross-cutting timing logic?
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, tap } from 'rxjs';

@Injectable()
export class TimingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable {
    const start = Date.now();
    return next.handle().pipe(
      tap(() => {
        const elapsed = Date.now() - start;
        console.log(`Request took ${elapsed}ms`);
      })
    );
  }
}
AThis interceptor logs time but does not call next.handle(), so no handler runs.
BThis interceptor measures time only before the handler, missing after completion.
CThis interceptor correctly measures time before and after the handler using tap().
DThis interceptor should use setTimeout instead of tap() to measure time.
Step-by-Step Solution
Solution:
  1. Step 1: Understand timing measurement

    The interceptor records start time before calling next.handle() and uses tap() to run code after the handler completes.
  2. Step 2: Confirm correct usage of RxJS tap()

    The tap() operator runs side effects after the observable emits, so it correctly logs elapsed time after the request finishes.
  3. Final Answer:

    This interceptor correctly measures time before and after the handler using tap(). -> Option C
  4. Quick Check:

    Timing with tap() after handler = A [OK]
Quick Trick: Use tap() after next.handle() to measure elapsed time [OK]
Common Mistakes:
  • Measuring time only before handler
  • Not returning next.handle() observable
  • Using setTimeout instead of RxJS operators

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes