Pipeline request NestJS
Ringkasan satu halaman untuk dibaca ulang menjelang interview. Dari Lesson 0021 (urutan dan binding), 0022 (pipe), 0023 (guard dan middleware), dan 0024 (interceptor dan filter). Latihan penuhnya: mock 0041.
Urutan eksekusi satu request
Dokumentasi Nest: "a request flows through middleware, then guards, then interceptors, then pipes, and finally back through interceptors on the return path." [1] Exception filter hanya bekerja kalau ada exception yang tidak ditangkap di langkah mana pun. Guard jalan "after all middleware, but before any interceptor or pipe." [2]
Kebutuhan → pakai yang mana
| Kebutuhan | Pakai | Alasan singkat |
|---|---|---|
| Logging akses, correlation id, CORS, body parser | Middleware | Berlaku untuk setiap request mentah; tidak perlu tahu handler |
| Autentikasi (token valid?) | Guard | Menolak sebelum ada kerja lain; lempar UnauthorizedException (401) |
| Otorisasi role (hanya admin, dsb.) | Guard | @Roles('admin') dibaca guard: punya ExecutionContext, membaca metadata handler lewat Reflector; false → ForbiddenException (403) |
| Validasi body/DTO | Pipe | ValidationPipe + class-validator; whitelist membuang properti asing, forbidNonWhitelisted menolaknya (400) |
| Ubah tipe parameter ("42" → 42) | Pipe | ParseIntPipe, ParseUUIDPipe per parameter |
| Bentuk response seragam ({ data: … }) | Interceptor | Membungkus handler; memetakan hasil dengan operator RxJS setelah next.handle() |
| Durasi request, timeout, cache response | Interceptor | Punya bagian sebelum dan sesudah handler |
| Format error yang konsisten | Exception filter | Mengubah exception yang lolos menjadi response error |
Kenapa otorisasi di guard, bukan middleware: middleware tidak tahu handler mana yang akan dipanggil setelah next(), sedangkan guard tahu. [2] Akibat urutan: user tanpa role yang mengirim body tidak valid mendapat 403, bukan 400.
Binding: global, controller, method
| Cara | Contoh | Catatan |
|---|---|---|
| Global tanpa DI | app.useGlobalGuards(), useGlobalPipes() di main.ts | Di luar module: tidak bisa meng-inject dependency |
| Global dengan DI | { provide: APP_GUARD, useClass: RolesGuard } (juga APP_PIPE, APP_INTERCEPTOR, APP_FILTER) | Terdaftar sebagai provider, DI berjalan |
| Controller / method | @UseGuards(), @UsePipes(), @UseInterceptors(), @UseFilters() | Pipe juga bisa per parameter: @Param('id', ParseIntPipe) |
| Middleware | configure(consumer) + consumer.apply(...).forRoutes(...), atau app.use() | Tidak lewat decorator [3] |
Urutan di dalam satu jenis komponen
- Guard, interceptor (sebelum), pipe: global → controller → method; pipe parameter paling akhir.
- Interceptor (sesudah): terbalik, method → controller → global, "in a first-in, last-out manner." [1]
- Exception filter: dari level terendah: method → controller → global. Exception yang Anda tangkap sendiri dengan
try/catchtidak sampai ke filter.
[1] NestJS docs: Request lifecycle · [2] NestJS docs: Guards · [3] NestJS docs: Middleware
Cheat sheet lain: urutan event loop · tahapan CRUD · Indeks