Complete the code to create a basic interceptor class in NestJS.
import { Injectable, [1] } from '@nestjs/common'; @Injectable() export class LoggingInterceptor implements [1] { intercept(context: any, next: any) { console.log('Before...'); return next.handle(); } }
The interceptor class must implement the NestInterceptor interface from NestJS to add cross-cutting logic.
Complete the code to add logic before and after the request handling in an interceptor.
intercept(context: any, next: any) {
console.log('Before...');
return next.handle().pipe([1](() => console.log('After...')));
}map which changes data instead of just running side effects.filter or reduce which are not for side effects.The tap operator from RxJS lets you run code after the observable completes without changing the data.
Fix the error in the interceptor code by completing the missing import.
import { Injectable, NestInterceptor, ExecutionContext, [1] } from '@nestjs/common'; import { Observable } from 'rxjs';
The CallHandler interface is needed to type the next parameter in the intercept method.
Fill both blanks to create a logging interceptor that measures execution time.
intercept(context: ExecutionContext, next: [1]): Observable<any> { const now = Date.now(); return next.handle().pipe([2](() => console.log(`Execution time: ${Date.now() - now}ms`))); }
map instead of tap for logging.The next parameter is typed as CallHandler, and tap is used to log after the request completes.
Fill all three blanks to create a caching interceptor that stores and returns cached responses.
import { Injectable, NestInterceptor, ExecutionContext, [1] } from '@nestjs/common'; import { Observable, of } from 'rxjs'; import { tap } from 'rxjs/operators'; @Injectable() export class CacheInterceptor implements NestInterceptor { private cache = new Map(); intercept(context: ExecutionContext, next: [2]): Observable<any> { const key = context.getHandler().name; if (this.cache.has(key)) { return [3](this.cache.get(key)); } return next.handle().pipe(tap((value) => { this.cache.set(key, value); })); }
The CallHandler type is used for the next parameter, and of from RxJS returns an observable of the cached value.