Performance: Interceptor interface
Interceptors affect the response time and rendering speed by controlling request handling and response transformation in NestJS applications.
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable() export class EfficientInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { // Minimal synchronous work return next.handle().pipe( map(data => { // Lightweight transformation return { ...data, intercepted: true }; }) ); } }
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable() export class SlowInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { // Heavy synchronous processing before passing for (let i = 0; i < 1e7; i++) {} return next.handle().pipe( map(data => { // Heavy synchronous processing on response for (let i = 0; i < 1e7; i++) {} return data; }) ); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous processing in interceptor | N/A | N/A | Blocks event loop delaying response | [X] Bad |
| Lightweight asynchronous interceptor logic | N/A | N/A | Non-blocking, fast response | [OK] Good |
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, tap } from 'rxjs';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
console.log('Before handler');
return next.handle().pipe(
tap(() => console.log('After handler'))
);
}
}import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class ErrorInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
try {
return next.handle();
} catch (error) {
console.error('Error caught:', error);
throw error;
}
}
}response.duration. Which approach correctly implements this?Pass the test and this pattern moves unknown