Request Lifecycle၊ Guards နှင့် Interceptors

12.6.0

Nest က controller မတိုင်ခင်နဲ့ ပြီးတဲ့နောက် handler အမျိုးမျိုး run ပါတယ်။ အလုပ်တစ်ခုစီကို သင့်တော်တဲ့အဆင့်မှာ ထားပါ။

ဒီစာမျက်နှာမှာ

Request က Controller ဆီ ရောက်ပုံ

ပုံမှန် request က middleware၊ guards၊ interceptors ရဲ့ အဝင်ဘက်၊ pipes အစဉ်အတိုင်း ဖြတ်ပြီး handler ဆီ ရောက်ပါတယ်။ Response က interceptors ကနေ ပြန်ထွက်ပါတယ်။ မဖမ်းထားတဲ့ exception ကို filters က ကိုင်တွယ်နိုင်ပါတယ်။

import {
  Controller, Get, Param, ParseIntPipe, UseGuards, UseInterceptors
} from "@nestjs/common";
import { SessionGuard } from "./session.guard";
import { TimingInterceptor } from "./timing.interceptor";

// Request: middleware -> guard -> interceptor -> pipe -> handler
// Response: handler -> interceptor -> client
@UseGuards(SessionGuard)
@UseInterceptors(TimingInterceptor)
@Controller("products")
export class ProductsController {
  @Get(":id")
  findOne(@Param("id", ParseIntPipe) id: number) {
    return { id };
  }
}

Route Parameter ကို ဝင်ပေါက်မှာ Parse လုပ်ခြင်း

Route parameter ကို ကိန်းပြည့် ပြောင်းပြီး မမှန်တဲ့ input ငြင်းဖို့ ParseIntPipe သုံးပါ။ Guard က handler run လို့ရမရ ဆုံးဖြတ်ပါတယ်။ ကြာချိန်တိုင်းတာတာ၊ response ပုံစံပြောင်းတာလို handler မတိုင်ခင်နဲ့ ပြီးတဲ့နောက် လုပ်ရမယ့်အလုပ်အတွက် interceptor သုံးပါ။

import { Controller, Get, Param, ParseIntPipe } from "@nestjs/common";

@Controller("products")
export class ProductsController {
  @Get(":id")
  read(@Param("id", ParseIntPipe) id: number) {
    return { id };
  }
}

တရားဝင် ကိုးကားချက်များ