Routes နှင့် HTTP Errors မှတ်တမ်းတင်ခြင်း

12.6.0

OpenAPI document က API ကို ဘယ်လိုခေါ်ရမလဲ ဖော်ပြပါတယ်။ Client တွေ အသုံးပြုမယ့် status codes နဲ့ payload ပုံစံတွေ ရေးထားပါ။

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

OpenAPI Document ပြသခြင်း

@nestjs/swagger ထည့်ပြီး bootstrap မှာ OpenAPI configuration ဆောက်ပါ။ SwaggerModule က document ထုတ်ပြီး Swagger UI ပြနိုင်ပါတယ်။ Request နဲ့ response DTO fields တွေအတွက် လိုအပ်သလို decorators သို့ CLI plugin သုံးပါ။

// At the top of main.ts
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";

// Inside bootstrap, after NestFactory.create(...)
const config = new DocumentBuilder()
  .setTitle("Catalog API")
  .setVersion("1.0")
  .build();

const documentFactory = () => SwaggerModule.createDocument(app, config);
SwaggerModule.setup("docs", app, documentFactory);

အမှားနဲ့ ကိုက်ညီတဲ့ Status ပြန်ခြင်း

Input မမှန်ရင် BadRequestException၊ resource မရှိရင် NotFoundException သုံးနိုင်ပါတယ်။ Error ပုံစံ တိကျသတ်မှတ်ချင်ရင် exception filter ထည့်ပါ။ အောင်မြင်တဲ့ response နဲ့ သိထားတဲ့ errors နှစ်မျိုးလုံးရဲ့ status နဲ့ body စမ်းပါ။

import { BadRequestException, NotFoundException } from "@nestjs/common";

function findProduct(id: number, products: Map<number, string>) {
  if (!Number.isInteger(id) || id < 1) {
    throw new BadRequestException("Use a positive integer product ID.");
  }

  const name = products.get(id);
  if (name === undefined) {
    throw new NotFoundException("Product not found.");
  }

  return { id, name };
}

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