Bird
0
0

You want to create a LoggingInterceptor that logs the request method, URL, and the time taken for each request. Which code snippet correctly implements this behavior?

hard📝 Best Practice Q15 of 15
NestJS - Interceptors
You want to create a LoggingInterceptor that logs the request method, URL, and the time taken for each request. Which code snippet correctly implements this behavior?
Aintercept(context, next) { const req = context.getRequest(); const now = Date.now(); next.handle().pipe( tap(() => console.log(`${req.method} ${req.url} - ${Date.now() - now}ms`)) ); }
Bintercept(context, next) { const req = context.switchToHttp().getRequest(); const now = Date.now(); return next.handle().pipe( tap(() => console.log(`${req.method} ${req.url} - ${Date.now() - now}ms`)) ); }
Cintercept(context, next) { const req = context.switchToHttp().getRequest(); const now = Date.now(); return next.handle().pipe( map(() => console.log(`${req.method} ${req.url} - ${Date.now() - now}ms`)) ); }
Dintercept(context, next) { const req = context.switchToHttp().getRequest(); const now = Date.now(); return next.handle().pipe( tap(() => console.error(`${req.method} ${req.url} - ${Date.now() - now}ms`)) ); }
Step-by-Step Solution
Solution:
  1. Step 1: Access request object correctly

    Use context.switchToHttp().getRequest() to get the HTTP request object in NestJS interceptors.
  2. Step 2: Use tap operator for side effects

    The tap operator is used to perform logging without altering the response stream. Using map or console.error is incorrect here.
  3. Final Answer:

    intercept(context, next) { const req = context.switchToHttp().getRequest(); const now = Date.now(); return next.handle().pipe( tap(() => console.log(`${req.method} ${req.url} - ${Date.now() - now}ms`)) ); } -> Option B
  4. Quick Check:

    Use switchToHttp(), tap, and return next.handle() [OK]
Quick Trick: Use switchToHttp().getRequest() and tap for logging [OK]
Common Mistakes:
  • Not returning next.handle()
  • Using map instead of tap
  • Using console.error instead of console.log
  • Incorrect request object access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes