Bird
0
0

How would you implement an interceptor in NestJS to log the duration of a request handler's execution?

hard📝 Application Q8 of 15
NestJS - Interceptors
How would you implement an interceptor in NestJS to log the duration of a request handler's execution?
AModify the request object to include a timestamp and log it in the controller.
BLog the time immediately before returning next.handle() without any RxJS operators.
CUse setTimeout to delay the handler and then log the time.
DRecord start time before next.handle(), then use RxJS tap operator to log elapsed time after response.
Step-by-Step Solution
Solution:
  1. Step 1: Capture start time before calling next.handle()

    This marks when the request processing begins.
  2. Step 2: Use RxJS tap operator on the observable returned by next.handle()

    This allows executing side effects after the handler completes.
  3. Step 3: Calculate and log elapsed time inside tap

    Subtract start time from current time to get duration.
  4. Final Answer:

    Record start time before next.handle(), then use RxJS tap operator to log elapsed time after response. correctly describes this approach.
  5. Quick Check:

    Use RxJS tap to log after handler completes [OK]
Quick Trick: Use RxJS tap to log time after next.handle() completes [OK]
Common Mistakes:
  • Logging time before next.handle() completes
  • Using setTimeout which is unrelated
  • Modifying request object instead of using interceptor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes