Reference · Node.js · Pipeline request NestJS

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

Middleware→ Guard→ Interceptor (sebelum)→ Pipe→ Handler→ Interceptor (sesudah)→ Exception filter

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

KebutuhanPakaiAlasan singkat
Logging akses, correlation id, CORS, body parserMiddlewareBerlaku untuk setiap request mentah; tidak perlu tahu handler
Autentikasi (token valid?)GuardMenolak 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/DTOPipeValidationPipe + class-validator; whitelist membuang properti asing, forbidNonWhitelisted menolaknya (400)
Ubah tipe parameter ("42" → 42)PipeParseIntPipe, ParseUUIDPipe per parameter
Bentuk response seragam ({ data: … })InterceptorMembungkus handler; memetakan hasil dengan operator RxJS setelah next.handle()
Durasi request, timeout, cache responseInterceptorPunya bagian sebelum dan sesudah handler
Format error yang konsistenException filterMengubah 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

CaraContohCatatan
Global tanpa DIapp.useGlobalGuards(), useGlobalPipes() di main.tsDi 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)
Middlewareconfigure(consumer) + consumer.apply(...).forRoutes(...), atau app.use()Tidak lewat decorator [3]

Urutan di dalam satu jenis komponen

[1] NestJS docs: Request lifecycle · [2] NestJS docs: Guards · [3] NestJS docs: Middleware

Cheat sheet lain: urutan event loop · tahapan CRUD · Indeks