Trung BìnhNestJS iconNestJS

Interceptors trong NestJS hoạt động như thế nào? Nêu các use-case phổ biến.

Interceptors wrap việc thực thi handler, cho phép chạy code trước và sau handler. Chúng implement NestInterceptor với method intercept(context, next) trả về Observable. Gọi next.handle() để tiếp tục pipeline, dùng RxJS operators để transform.

Use-cases phổ biến: Response transform — dùng map() để wrap tất cả response trong object chuẩn { success: true, data, timestamp }. Logging — ghi thời gian xử lý với tap(). Caching — kiểm tra cache trước, nếu hit thì return of(cachedData) bỏ qua handler. Timeout — dùng timeout(5000) throw TimeoutError sau 5 giây. Error mapping — catchError() để transform exceptions.

Apply với @UseInterceptors() ở route/controller hoặc global qua APP_INTERCEPTOR. Khác Guard và Pipe, Interceptors chạy cả trước lẫn sau handler nên có thể transform response.

Xem toàn bộ NestJS cùng filter theo level & chủ đề con.

Mở danh sách NestJS