intermediate
NestJS interceptors
Применяйте interceptors для cross-cutting request/response behavior: logging, mapping, timing, caching и wrapping streams.
Interceptors оборачивают pipeline handler после guards; на outbound могут трансформировать результат, логировать, мерить latency. Реализуют `NestInterceptor` с `intercept(context, next)`.
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler) {
const start = Date.now();
return next.handle().pipe(
tap(() => logger.log(`${Date.now() - start}ms`)),
);
}
}
Interceptors для response mapping (обёртка `{ data }`), caching, timeout, RxJS stream transforms. При композиции с operators работают и на success, и на error paths.
На интервью: interceptors vs middleware (видят handler и return value), vs filters (exceptions), когда RxJS оправдан.
Типовые ошибки: business logic в interceptors, забыли что при reject guards interceptor не запускается, неограниченные RxJS subscriptions.
Компромисс — между простотой, производительностью, безопасностью и эксплуатацией: назовите, что оптимизировали и какую цену приняли.
Чеклист:
- Cross-cutting response behavior в interceptors.
- tap/map для logging и shaping.
- Не заменять guards или pipes interceptors.
- Stateless interceptors где возможно.