Requests Validate လုပ်ပြီး Routes စမ်းခြင်း

12.6.0

API ဝင်ပေါက်မှာ inputs တွေကို စစ်ပါ။ Input မမှန်ရင်၊ record မရှိရင် သင့်တော်တဲ့ HTTP status ပြန်ပါ။

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

DTO နဲ့ Validation Pipe သုံးခြင်း

ValidationPipe အတွက် class-validator နဲ့ class-transformer ထည့်ပါ။ DTO ကို class နဲ့ရေးပြီး validation decorators ထည့်ပါ။ whitelist ဖွင့်ရင် validation decorator မပါတဲ့ properties ကို ဖယ်ပါတယ်။ အဲဒါတွေကို ငြင်းဖို့ forbidNonWhitelisted ပေါင်းပါ။

import { Body, Controller, Post, ValidationPipe } from "@nestjs/common";
import { IsInt, IsNotEmpty, IsString, Min } from "class-validator";

class CreateOrderDto {
  @IsString()
  @IsNotEmpty()
  item!: string;

  @IsInt()
  @Min(1)
  quantity!: number;
}

@Controller("orders")
export class OrdersController {
  @Post()
  create(@Body(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
    input: CreateOrderDto) {
    return input;
  }
}

မှန်တဲ့ Requests နဲ့ မှားတဲ့ Requests နှစ်မျိုး စစ်ခြင်း

Service logic ကို သီးသန့်စမ်းပါ။ HTTP route ကို end-to-end test နဲ့ စမ်းပြီး request parsing၊ validation၊ status နဲ့ response ကို တွဲစစ်ပါ။ မှန်တဲ့ body နဲ့ quantity 0 လို မမှန်တဲ့ body နှစ်မျိုးလုံး စမ်းပါ။

// In the end-to-end suite with the Nest application started.
import request from "supertest";

it("accepts an order with a positive quantity", async () => {
  const order = { item: "Notebook", quantity: 2 };
  await request(app.getHttpServer()).post("/orders").send(order).expect(201, order);
});

it("rejects an order with quantity zero", async () => {
  await request(app.getHttpServer())
    .post("/orders")
    .send({ item: "Notebook", quantity: 0 })
    .expect(400);
});

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