Junior — Middle
Explain the concept of Interceptor in the NestJS framework and its main functions
sobes.tech AI
Answer from AI
In NestJS, an Interceptor is a class that allows you to intercept and process incoming requests and outgoing responses. The main functions of Interceptors:
- Modifying or transforming response data before sending it to the client.
- Logging and monitoring request execution time.
- Caching request results.
- Handling errors and exceptions.
- Adding additional logic before and after calling the route handler.
An Interceptor implements the NestInterceptor interface and the intercept(context, next) method, where you can execute code before and after calling the next handler.
Example of a simple Interceptor that logs request execution time:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const now = Date.now();
return next
.handle()
.pipe(
tap(() => console.log(`Request handled in ${Date.now() - now}ms`))
);
}
}
Interceptors help centrally manage the behavior of requests and responses in the application.