Thuta Learning
API Tutorial
ProjectsWeb Developmentအလယ်အလတ်

Mini Project — Part 2: CRUD Feature ထည့်ခြင်း

API Tutorialသင်ခန်းစာ 3040 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • POST နဲ့ PATCH request တွေကို JSON body နဲ့ Content-Type header ပါပါ ပို့နိုင်ဖို့
  • 204 No Content response ကို res.json() မခေါ်ဘဲ ကိုင်တွယ်နိုင်ဖို့
  • 422 response ထဲက field အလိုက် အသေးစိတ်ကို ဖတ်ပြီး 409 conflict ကို ApiError ကနေ ခွဲသိနိုင်ဖို့
  • Command-line argument တွေကို client call တွေနဲ့ map လုပ်ပြီး ရလဒ်တစ်ခုစီအတွက် ဖတ်လို့ရတဲ့ line တစ်ကြောင်း print လုပ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Part 1 က ဖတ်ရုံပဲ လုပ်နိုင်ခဲ့ပါတယ်။ Part 2 မှာ data ကို ပြောင်းတဲ့ verb သုံးခု ထပ်ထည့်ပါမယ်၊ ဖန်တီးဖို့ POST၊ ပြင်ဖို့ PATCH၊ ဖျက်ဖို့ DELETE ပါ။ request() က Authorization header ကို ထည့်ပေးပြီးသားမို့ အဲဒါ မပြောင်းပါဘူး။ ဒါကြောင့် code အသစ်က အချက်နှစ်ချက်အကြောင်းပါ၊ body ထဲမှာ ဘာပါမလဲနဲ့ ပြန်လာတာက ဘာလဲ။

ကောင်တာက form တစ်ရွက်ကို စဉ်းစားကြည့်ပါ။ Create လုပ်ရင် form အသစ်တစ်ရွက် ပေးပါတယ်၊ edit လုပ်ရင် ပြောင်းတဲ့ box တွေကိုပဲ ပေးပါတယ်၊ delete လုပ်ရင် form နံပါတ်ကလွဲပြီး ဘာမှ မပေးပါဘူး။ အဲဒီအတွက် စာရေးက ဖတ်လို့ရတဲ့ အဖြေ ပြန်ပေးဖို့ လိုပါတယ်၊ တံဆိပ်ခတ်ပြီးပြီ၊ box တစ်ခု ကျန်လို့ ပယ်ချတယ်၊ ဒါမှမဟုတ် 'ဒီနံပါတ် မရှိဘူး' ဆိုပြီးပေါ့။

Problem → Why → Solution

ပြဿနာ: fetch ကို သုံးကြိမ် copy ကူးထားတာ

အစီအစဉ်မရှိရင် function အသစ်သုံးခုကို fetch ကို သီးခြား copy သုံးခုအဖြစ် ရေးမိတတ်ပါတယ်။ Copy တစ်ခုချင်းစီက Authorization header ကို မှတ်မိပေမယ့် တစ်ခုက Content-Type ကို မေ့သွားလို့ server က body ကို plain text အဖြစ် လက်ခံပြီး header အကြောင်း ဘာမှမပါတဲ့ error နဲ့ ပြန်ဖြေပါတယ်။ Delete function က body မပါတဲ့ 204 response ပေါ်မှာ res.json() ကို ခေါ်လို့ delete အောင်မြင်ပေမယ့် throw ဖြစ်ပြီး ကျရှုံးသလို မြင်ရပါတယ်။

Validation မအောင်ရင်လည်း သင်ယူသူက status နံပါတ်ပဲ မြင်ရပါတယ်။ ဘယ် field မှားလဲ။ ဘယ်သူမှ မသိပါဘူး၊ ဘာကြောင့်လဲဆိုတော့ အသေးစိတ်က copy ကူးထားတဲ့ code က ဘယ်တော့မှ မဖတ်တဲ့ response body ထဲမှာ ရှိနေလို့ပါ။

draft.js
// Three copies of fetch: the bugs hide in the details
async function createUser(name, email) {
  const res = await fetch(`${BASE}/users`, {
    method: "POST",
    headers: { Authorization: `Bearer ${TOKEN}` }, // no Content-Type
    body: JSON.stringify({ name, email }),
  });
  return res.json();
}

async function deleteUser(id) {
  const res = await fetch(`${BASE}/users/${id}`, { method: "DELETE", headers: AUTH });
  return res.json(); // 204 has no body, so this throws after a SUCCESSFUL delete
}

အမှားတွေက အသေးစိတ်ထဲမှာ ဘာကြောင့် ပုန်းနေတာလဲ

အမှားတွေအားလုံးက request() ကိုယ်တိုင် ကိုင်လို့ရတဲ့ အသေးစိတ်တွေထဲမှာပါ၊ content type၊ 204 စည်းမျဉ်းနဲ့ error parsing တို့ပါ။ ဒါတွေကို တစ်နေရာတည်းမှာ စုလိုက်ရင် function အသစ်တစ်ခုစီက တစ်ကြောင်းတည်း ဖြစ်သွားပြီး fix တစ်ခုက အားလုံးကို ရောက်ပါတယ်။

Core concept: body ဝင်ပြီး status ထွက်တယ်

Write request မှာ read request မှာမရှိတဲ့ တစ်ဝက်နှစ်ဝက် ရှိပါတယ်။ Request ဘက်က body ပါ၊ ဖန်တီးမယ့် ဒါမှမဟုတ် ပြောင်းမယ့် data ကို JSON နဲ့ ဖော်ပြပြီး JSON.stringify နဲ့ serialise လုပ်ကာ Content-Type: application/json နဲ့ ကြေညာရပါတယ်။ fetch က ခန့်မှန်းမပေးပါဘူး။ String body ပေးရင် text/plain လို့ label ကပ်ပေးပြီး တင်းကျပ်တဲ့ server က ငြင်းပါတယ်။ Response ဘက်က အောင်မြင်တာထက် ပိုတဲ့ အဓိပ္ပာယ်ပါတဲ့ status code ပါ၊ 201 က ဖန်တီးပြီး၊ 204 က ပြီးပြီ ပြန်ပေးစရာ မရှိ၊ 404 က record မရှိ၊ 409 က ရှိပြီးသား data နဲ့ ပဋိပက္ခ၊ 422 က data က validation မအောင်လို့ ဖြစ်ပါတယ်။

Requestပို့တဲ့ bodyကိုင်တွယ်ရမယ့် အဖြေများ
POST /usersuser အသစ်အပြည့်အစုံပါတဲ့ JSON201 နဲ့ ဖန်တီးပြီး user၊ 409 email ထပ်နေ၊ 422 field မမှန်
PATCH /users/:idပြောင်းတဲ့ field တွေပဲပါတဲ့ JSON200 နဲ့ ပြင်ပြီး user၊ 404 id မသိ၊ 422 field မမှန်
DELETE /users/:idမပါbody မပါတဲ့ 204၊ 404 id မသိ

၁။ Body ကို optional လက်ခံပါ

request(method, route, body) က body က undefined မဟုတ်မှ Content-Type ထည့်ပြီး JSON.stringify ကို ခေါ်ပါတယ်။ ဒါကြောင့် GET နဲ့ DELETE က body လုံးဝ မပို့တာကို ဆက်လုပ်နိုင်ပါတယ်။

၂။ 204 အတွက် null ပြန်ပါ

Parse မလုပ်ခင် status ကို စစ်ပါ။ 204 response မှာ body မရှိတာ အဓိပ္ပာယ်ကိုက်ပါ၊ body ဗလာပေါ်မှာ res.json() ခေါ်ရင် SyntaxError တက်ပါတယ်။

၃။ Field အသေးစိတ်ကို သိမ်းထားပါ

422 body မှာ error.fields ပါပါတယ်၊ ဥပမာ { email: "invalid" }။ ApiError က အဲဒါကို သိမ်းထားလို့ CLI က 422 ပဲမဟုတ်ဘဲ email: invalid လို့ print လုပ်နိုင်ပါတယ်။

PATCH နဲ့ PUT က မတူပါဘူး။ PUT က resource တစ်ခုလုံးကို အစားထိုးတာမို့ client က field အားလုံး ပို့ရပါတယ်။ PATCH က ပြောင်းတာကိုပဲ ပို့ပါတယ်။ update u_6 email=new@example.com ဆိုတဲ့ CLI command က တစ်စိတ်တစ်ပိုင်း ပြောင်းတာမို့ PATCH က ပိုသင့်တော်ပါတယ်။ API က PUT ပဲပေးရင် user ကို အရင်ဖတ်၊ ပြောင်းလဲမှုကို merge လုပ်ပြီး merge လုပ်ပြီးသား object ကို ပြန်ပို့ပါ။

Command-line layer ကို ရည်ရွယ်ချက်ရှိရှိ ပါးပါးထားပါတယ်။ runCommand(client, argv) က script နာမည်နောက်က argument တွေကို လက်ခံပြီး (တကယ့် program မှာ process.argv.slice(2) ပါ)၊ command နာမည်နဲ့ client function ကို ရွေးကာ print လုပ်ရမယ့် line ကို return ပြန်ပါတယ်။ Print မလုပ်ဘဲ string ပြန်ပေးတာမို့ demo က၊ နောက်ပိုင်း test တွေက ရလဒ်ကို စစ်နိုင်ပါတယ်။ Catch block တစ်ခုတည်းက ApiError ကို 409 CONFLICT: Email already in use အဖြစ် ပြောင်းပေးပါတယ်။

Mental model: body ဝင်၊ status ထွက်
  1. ပြောင်းလဲမှုကို JSON body နဲ့ ဖော်ပြ
  2. request() က Content-Type ထည့်ပြီး ပို့
  3. Status က ဆုံးဖြတ်: 2xx data၊ 4xx ApiError
  4. CLI က ဖတ်လို့ရတဲ့ line တစ်ကြောင်း print

Write တိုင်းက round trip တူတူပါ၊ data က JSON အဖြစ် ထွက်သွားပြီး status က ဖန်တီးပြီး၊ ပြောင်းပြီး၊ ဖျက်ပြီး၊ ငြင်းခံရပြီ ဆိုတဲ့ လေးခုထဲက ဘယ်ဟာလဲ ပြောပါတယ်။

အခြေခံ ပုံစံ

javascript
async function request(method, route, body) {
  // headers; add Content-Type + JSON.stringify only when body !== undefined
  // 204 -> return null; !res.ok -> throw ApiError(status, code, message, { fields })
}

const create = async (input) => (await request("POST", "/things", input)).data;
const change = async (id, patch) => (await request("PATCH", `/things/${id}`, patch)).data;
const remove = async (id) => { await request("DELETE", `/things/${id}`); };

request() ကို body ယူနိုင်၊ 204 ကို ကိုင်နိုင်၊ error အသေးစိတ်ကို သိမ်းနိုင်အောင် တစ်ကြိမ်ပဲ ချဲ့ပါတယ်။ ဒါဆို endpoint function တစ်ခုစီက verb၊ route နဲ့ data ကို ညွှန်ပြတဲ့ တစ်ကြောင်းတည်း ဖြစ်သွားပါတယ်။

Part 2 code: write route တွေနဲ့ command-line layer

ဒါက Part 2 ရဲ့ file အပြည့်အစုံပါ။ Mock API မှာ validation ပါတဲ့ write route တွေ ထပ်ပါလာလို့ client မှာ ပြောစရာ ရှိပါပြီ။ NEW လို့ မှတ်ထားတဲ့ line တွေ ဒါမှမဟုတ် >>> NEW နဲ့ <<< end ကြားက line တွေက ဒီအပိုင်းမှာ ထပ်ထည့်တာပါ၊ ကျန်တာတွေက request() မှာ body parameter တစ်ခု ပိုလာတာကလွဲရင် Part 1 အတိုင်းပါပဲ။ Run ပြီး output ကို အပေါ်ကနေ အောက်ကို ဖတ်ကြည့်ပါ။ Duplicate တစ်ခု၊ မမှန်တဲ့ email တစ်ခု၊ ဖျက်ပြီးသားကို ထပ်ဖျက်တာနဲ့ ပုံစံမမှန်တဲ့ command တစ်ခုကို ရည်ရွယ်ချက်ရှိရှိ စမ်းထားပါတယ်။

part2.mjs
// user-cli, part 2: create / update / delete + a tiny command-line layer.
// Save as part2.mjs and run: node part2.mjs   (Node 20.12 or newer)
// Lines marked NEW (or between ">>> NEW" and "<<< end") were added in this part.
import http from "node:http";

// ===== 1. Mock API: now with write routes =====
const TOKEN = "demo-token-123";
const users = [
  { id: "u_1", name: "Alice", email: "alice@example.com" },
  { id: "u_2", name: "Bob", email: "bob@example.com" },
  { id: "u_3", name: "Chidi", email: "chidi@example.com" },
  { id: "u_4", name: "Dara", email: "dara@example.com" },
  { id: "u_5", name: "Eli", email: "eli@example.com" },
];
let nextId = 6; // NEW

function send(res, status, body) {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(body));
}
function fail(res, status, code, message, fields) { // NEW: optional fields
  send(res, status, { error: { code, message, ...(fields && { fields }) } });
}

// >>> NEW in part 2: body parsing and validation for the mock
async function readJson(req) {
  let raw = "";
  for await (const chunk of req) raw += chunk;
  return raw ? JSON.parse(raw) : {}; // throws SyntaxError on malformed JSON
}
function validate(input, partial) {
  const fields = {};
  if (!partial || "name" in input) {
    if (typeof input.name !== "string" || !input.name.trim()) fields.name = "required";
  }
  if (!partial || "email" in input) {
    if (typeof input.email !== "string" || !/^[^@\s]+@[^@\s]+$/.test(input.email)) {
      fields.email = "invalid";
    }
  }
  return fields;
}
// <<< end of new mock helpers

const mock = http.createServer(async (req, res) => {
  if (req.headers.authorization !== `Bearer ${TOKEN}`) {
    return fail(res, 401, "UNAUTHORIZED", "Missing or invalid token");
  }
  const url = new URL(req.url, "http://mock");
  const one = url.pathname.match(/^\/v1\/users\/([\w-]+)$/);
  const found = one && users.find((u) => u.id === one[1]);
  try {
    if (req.method === "GET" && url.pathname === "/v1/users") {
      const page = Number(url.searchParams.get("page") ?? 1);
      const limit = Number(url.searchParams.get("limit") ?? 10);
      const data = users.slice((page - 1) * limit, page * limit);
      return send(res, 200, { data, meta: { page, limit, total: users.length } });
    }
    // >>> NEW in part 2: POST /v1/users
    if (req.method === "POST" && url.pathname === "/v1/users") {
      const input = await readJson(req);
      const fields = validate(input, false);
      if (Object.keys(fields).length) {
        return fail(res, 422, "VALIDATION_ERROR", "Invalid user data", fields);
      }
      if (users.some((u) => u.email === input.email)) {
        return fail(res, 409, "CONFLICT", "Email already in use");
      }
      const user = { id: `u_${nextId++}`, name: input.name.trim(), email: input.email };
      users.push(user);
      return send(res, 201, { data: user });
    }
    // <<< end of POST
    if (one && !found) return fail(res, 404, "NOT_FOUND", `User ${one[1]} not found`);
    if (req.method === "GET" && found) return send(res, 200, { data: found });
    // >>> NEW in part 2: PATCH and DELETE /v1/users/:id
    if (req.method === "PATCH" && found) {
      const changes = await readJson(req);
      const fields = validate(changes, true);
      if (Object.keys(fields).length) {
        return fail(res, 422, "VALIDATION_ERROR", "Invalid user data", fields);
      }
      if (changes.name) found.name = changes.name.trim();
      if (changes.email) found.email = changes.email;
      return send(res, 200, { data: found });
    }
    if (req.method === "DELETE" && found) {
      users.splice(users.indexOf(found), 1);
      res.writeHead(204);
      return res.end(); // 204 No Content: no body at all
    }
    // <<< end of PATCH and DELETE
    fail(res, 404, "NOT_FOUND", "No such route");
  } catch (err) {
    if (err instanceof SyntaxError) {
      return fail(res, 400, "INVALID_JSON", "Body is not JSON");
    }
    fail(res, 500, "INTERNAL", "Unexpected server error");
  }
});

// ===== 2. The client library =====
class ApiError extends Error {
  constructor(status, code, message, extra = {}) { // NEW: extra
    super(message);
    this.name = "ApiError";
    this.status = status;
    this.code = code;
    this.fields = extra.fields; // NEW
  }
}

function loadConfig(env = process.env) {
  const token = env.API_TOKEN;
  if (!token) throw new Error("API_TOKEN is not set (put it in .env, never in code)");
  return { baseUrl: env.API_BASE_URL ?? "https://api.example.com/v1", token };
}

function createClient({ baseUrl, token }) {
  async function request(method, route, body) { // NEW: optional body
    const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
    if (body !== undefined) headers["Content-Type"] = "application/json"; // NEW
    const res = await fetch(`${baseUrl}${route}`, {
      method,
      headers,
      body: body === undefined ? undefined : JSON.stringify(body), // NEW
    });
    if (res.status === 204) return null; // NEW: nothing to parse
    const payload = await res.json();
    if (!res.ok) {
      const { code, message, fields } = payload.error;
      throw new ApiError(res.status, code, message, { fields });
    }
    return payload;
  }
  const userPath = (id) => `/users/${encodeURIComponent(id)}`;
  return {
    listUsers({ page = 1, limit = 10 } = {}) {
      return request("GET", `/users?page=${page}&limit=${limit}`);
    },
    async getUser(id) {
      return (await request("GET", userPath(id))).data;
    },
    // >>> NEW in part 2
    async createUser(input) {
      return (await request("POST", "/users", input)).data;
    },
    async updateUser(id, changes) {
      return (await request("PATCH", userPath(id), changes)).data;
    },
    async deleteUser(id) {
      await request("DELETE", userPath(id));
    },
    // <<< end new
  };
}

// >>> NEW in part 2: the command-line layer (argv is process.argv.slice(2))
function parsePairs(pairs) {
  const changes = {};
  for (const pair of pairs) {
    const i = pair.indexOf("=");
    if (i < 1) throw new Error(`expected key=value, got "${pair}"`);
    changes[pair.slice(0, i)] = pair.slice(i + 1);
  }
  return changes;
}

const show = (u) => `${u.id}: ${u.name} <${u.email}>`;

function describeFields(fields) {
  if (!fields) return "";
  return ` (${Object.entries(fields).map(([k, v]) => `${k}: ${v}`).join(", ")})`;
}

async function runCommand(client, argv) {
  const [cmd, ...args] = argv;
  try {
    switch (cmd) {
      case "list": {
        const { data, meta } = await client.listUsers();
        return `${data.map((u) => u.name).join(", ")} (${meta.total} total)`;
      }
      case "get":
        return show(await client.getUser(args[0]));
      case "create": {
        const user = await client.createUser({ name: args[0], email: args[1] });
        return `created ${show(user)}`;
      }
      case "update": {
        const user = await client.updateUser(args[0], parsePairs(args.slice(1)));
        return `updated ${show(user)}`;
      }
      case "delete":
        await client.deleteUser(args[0]);
        return `deleted ${args[0]} (204)`;
      default:
        return `unknown command: ${cmd ?? "(none)"}`;
    }
  } catch (err) {
    if (!(err instanceof ApiError)) return `error: ${err.message}`;
    return `${err.status} ${err.code}: ${err.message}${describeFields(err.fields)}`;
  }
}
// <<< end of command-line layer

// ===== 3. Demo: pretend these arrays came from process.argv.slice(2) =====
await new Promise((resolve) => mock.listen(0, "127.0.0.1", resolve));
try {
  const { port } = mock.address();
  const env = { API_BASE_URL: `http://127.0.0.1:${port}/v1`, API_TOKEN: TOKEN };
  const client = createClient(loadConfig(env));
  const commands = [
    ["create", "Fiona", "fiona@example.com"],
    ["create", "Fiona", "fiona@example.com"],
    ["create", "Gus", "not-an-email"],
    ["update", "u_6", "email=fiona@work.example.com"],
    ["get", "u_6"],
    ["delete", "u_6"],
    ["get", "u_6"],
    ["delete", "u_6"],
    ["update", "u_1", "email"],
    ["list"],
  ];
  for (const argv of commands) {
    console.log(`$ user-cli ${argv.join(" ")}`);
    console.log(await runCommand(client, argv));
  }
} finally {
  mock.close();
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Declare the body typeif (body !== undefined) headers["Content-Type"] = "application/json";

    Body ပါမှသာ Content-Type ကို ထည့်ပါတယ်။ ဒီ line မရှိရင် fetch က string body ကို text/plain လို့ ပို့ပြီး server က ငြင်းပါလိမ့်မယ်။

  2. Nothing to parse on 204if (res.status === 204) return null;

    DELETE အောင်မြင်ရင် body မပါပါဘူး။ Parse မလုပ်ခင် ဒီ line က ထွက်သွားလို့ res.json() က အောင်မြင်တဲ့ delete ပေါ်မှာ ဘယ်တော့မှ မ throw ပါဘူး။

  3. Keep the field detailsthrow new ApiError(res.status, code, message, { fields });

    422 ရဲ့ error.fields ကို ApiError ထဲ ထည့်ပေးပါတယ်။ CLI က email: invalid လို့ print လုပ်ဖို့ ဒီအချက်အလက် လိုပါတယ်။

  4. PATCH sends only the changesreturn (await request("PATCH", userPath(id), changes)).data;

    updateUser() က ပြောင်းတဲ့ field တွေပါတဲ့ object ကိုပဲ ပို့ပြီး server ပြန်လာတဲ့ user ကို ပြန်ပေးပါတယ်။ { data } envelope ကို ဒီမှာ ဖွင့်ပေးလို့ caller က user ကိုပဲ မြင်ရပါတယ်။

  5. Split on the first = onlyconst i = pair.indexOf("=");

    email=a=b လို argument မှာ equals နှစ်ခုပါပါတယ်။ ပထမ = ကိုပဲ ရှာပြီး ကျန်တာအားလုံးကို value အဖြစ် ယူလို့ value ပြတ်မသွားပါဘူး။

  6. The mock enforces unique emailsif (users.some((u) => u.email === input.email)) {

    Mock က email တူတာကို 409 နဲ့ ငြင်းပါတယ်။ ဒါကြောင့် demo ထဲက ဒုတိယ create က conflict ကို တကယ်တွေ့ပြီး client ရဲ့ error path ကို စမ်းနိုင်ပါတယ်။

You should see
$ user-cli create Fiona fiona@example.com
created u_6: Fiona <fiona@example.com>
$ user-cli create Fiona fiona@example.com
409 CONFLICT: Email already in use
$ user-cli create Gus not-an-email
422 VALIDATION_ERROR: Invalid user data (email: invalid)
$ user-cli update u_6 email=fiona@work.example.com
updated u_6: Fiona <fiona@work.example.com>
$ user-cli get u_6
u_6: Fiona <fiona@work.example.com>
$ user-cli delete u_6
deleted u_6 (204)
$ user-cli get u_6
404 NOT_FOUND: User u_6 not found
$ user-cli delete u_6
404 NOT_FOUND: User u_6 not found
$ user-cli update u_1 email
error: expected key=value, got "email"
$ user-cli list
Alice, Bob, Chidi, Dara, Eli (5 total)

PUT, PATCH နဲ့ request ကို ထပ်ပို့ခြင်း

Write တွေက request တူတူကို နှစ်ကြိမ်ပို့ရင် ဘာဖြစ်လဲဆိုတာ ကွာပါတယ်၊ အဲဒီကွာခြားချက်က Part 3 မှာ failure တစ်ခုကနေ client က ဘယ်လို ပြန်လည်နိုင်လဲဆိုတာကို ဆုံးဖြတ်ပါတယ်။ Demo က နှစ်ကြိမ် ပြပါတယ်၊ ဒုတိယ create က 409 ရတာ server က email မထပ်အောင် စစ်လို့ပဲ ဖြစ်ပြီး ဒုတိယ delete က 404 ရတာ ပထမတစ်ခု အောင်မြင်ခဲ့လို့ပါ။

Methodနှစ်ကြိမ်ပို့ရင်Demo က ပြတာ
GETအဖြေတူ၊ ဘာမှ မပြောင်းဘယ်အချိန်မဆို ထပ်ပို့လို့ ဘေးကင်း
PUT, DELETEအဆုံးအခြေအနေ တူ၊ status ကွာနိုင်ဒုတိယ delete: 404၊ ဒါပေမယ့် user က ဘယ်လိုပဲဖြစ်ဖြစ် မရှိတော့
PATCHပြောင်းတာပေါ်မူတည်Email ကို နှစ်ခါ သတ်မှတ်တာ ပြဿနာမရှိ၊ counter ကို နှစ်ခါ 1 ပေါင်းတာကတော့ ရှိ
POSTပုံမှန်အားဖြင့် record ဒုတိယတစ်ခု ဖန်တီးဒုတိယ create: server က email စစ်လို့ပဲ 409

Script က user ပျောက်သွားဖို့ပဲ လိုတယ်ဆိုရင် DELETE ပေါ်က 404 က အောင်မြင်မှုကို ဖုံးထားတာပါ။ Error တွေကို လျစ်လျူရှုမယ့်အစား အဲဒါကို အောင်မြင်မှုအဖြစ် ထင်ရှားစွာ သဘောထားပါ။

422 body နဲ့ 204 response ကို ဖတ်ခြင်း

Validation error က လူတစ်ယောက် ပြင်နိုင်တဲ့ တစ်ခုတည်းသော failure မို့ ဖတ်လို့ရတဲ့ output ထိုက်တန်ပါတယ်။ Error body က မှားတဲ့ field တစ်ခုချင်းစီကို အကြောင်းပြချက်နဲ့ စာရင်းပေးထားပြီး code အနည်းငယ်နဲ့ အဲဒါကို အသုံးပြုသူ လုပ်ဆောင်နိုင်တဲ့ အရာအဖြစ် ပြောင်းလို့ရပါတယ်။

fields.mjs
// What a 422 body looks like, and how to turn it into lines a person can act on
const body = {
  error: {
    code: "VALIDATION_ERROR",
    message: "Invalid user data",
    fields: { email: "invalid", name: "required" },
  },
};

const lines = Object.entries(body.error.fields).map(([field, why]) => `${field}: ${why}`);
console.log(`${body.error.code} - ${body.error.message}`);
console.log(lines.join("\n"));

တစ်ခါ သက်သေပြသင့်တဲ့ နောက်အချက်က body မပါတဲ့ 204 ပါ။ အောက်က Response မှာ အောင်မြင်တဲ့ status ရှိပြီး body မရှိပါဘူး၊ ဒါကို JSON အဖြစ် parse လုပ်ကြည့်ရင် မအောင်မြင်ပါဘူး၊ request() က status ကို အရင်စစ်ရတာ အဲဒါကြောင့်ပါ။

no-content.mjs
// 204 No Content is a success with no body, so there is nothing for json() to read
const res = new Response(null, { status: 204 });
console.log("status:", res.status, "| ok:", res.ok);
try {
  await res.json();
} catch (err) {
  console.log(`${err.name}: ${err.message}`);
}

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ

ဒီလို admin script နဲ့ CLI သေးသေးလေးတွေက team အများစု API ကို ပထမဆုံး ထိတွေ့တဲ့ နည်းပါ၊ customer တွေရဲ့ CSV ကို import လုပ်၊ demo ပြီးနောက် test data ဖျက်၊ account တစ်စုကို နာမည်ပြောင်းတာတွေပါ။ Write function သုံးခုတူတူက web form တစ်ခုနောက်မှာလည်း ရှိပါတယ်၊ အဲဒီမှာ error.fields က UI ကို banner တစ်ခုတည်းပြတာအစား မအောင်မြင်တဲ့ input အတိအကျကို အမှတ်အသားပြခွင့်ပေးပါတယ်။

အကျင့်နှစ်ခုက production ကို ဆက်သွားပါတယ်။ delete လို ဖျက်ဆီးတဲ့ command တွေကို sandbox ဒါမှမဟုတ် staging environment ကို အရင်ညွှန်ပါ၊ ဘာလို့လဲဆိုတော့ DELETE က ပြန်မရနိုင်တဲ့ တစ်ခုတည်းသော request ပါ။ Provider က POST request အတွက် idempotency key ပေးထားရင် တစ်ခုပို့ပါ၊ ဘာကြောင့်လဲဆိုတော့ client က သတိထားမယ်လို့ မမျှော်ဘဲ server ဘက်မှာ ထပ်ပို့တဲ့ create ကို ဘေးကင်းစေလို့ပါ။

အမှားများ

ဖြစ်လေ့ရှိတဲ့ အမှားများ

JSON body မှာ Content-Type မေ့တာ

fetch က string body ကို text/plain;charset=UTF-8 လို့ label ကပ်ပြီး တင်းကျပ်တဲ့ server က 415 နဲ့ ဖြေ ဒါမှမဟုတ် body ကို လျစ်လျူရှုပါတယ်။ JSON ပို့တိုင်း Content-Type: application/json ကို သတ်မှတ်ပါ၊ request() က body ပါတဲ့ call တိုင်းအတွက် လုပ်ပေးပါတယ်။

204 ပေါ်မှာ res.json() ခေါ်တာ

အောင်မြင်တဲ့ delete က body မပါဘဲ ဖြေတာမို့ res.json() က SyntaxError: Unexpected end of JSON input ကို throw လုပ်ပြီး ကောင်းတဲ့ရလဒ်က ကျရှုံးသလို မြင်ရပါတယ်။ Parse မလုပ်ခင် status ကို စစ်ပါ။

key=value ကို split("=") နဲ့ ခွဲတာ

url=https://x.example/?a=b လို argument မှာ equals နှစ်ခုပါလို့ split က value ကို တစ်ဝက်ပိုင်းသွားပါတယ်။ indexOf နဲ့ ပထမ = ကိုရှာပြီး နောက်က အားလုံးကို value အဖြစ်ယူပါ၊ key မပါတဲ့ pair ကိုလည်း ပယ်ပါ။

Mini challenge

Create ကို နှစ်ကြိမ် run လည်း ဘေးကင်းအောင် လုပ်ပါ

User တူတူကို နှစ်ကြိမ် create လုပ်တဲ့ script က ဒုတိယအကြိမ်မှာ crash မဖြစ်သင့်ပါဘူး။ createUser ကို စမ်းကြည့်ပြီး server က 409 နဲ့ ဖြေရင် email နဲ့ ရှိပြီးသား user ကို ရှာပြီး return ပြန်တဲ့ ensureUser(client, input) ကို ရေးပါ။ တခြား error အားလုံး၊ 422 အပါအဝင် caller ဆီ ရောက်ရမယ်။

  • User အသစ်ဆိုရင် ensureUser က { user, created: true } ကို return ပြန်ရမယ်
  • ApiError status 409 မှာ listUsers ကို page လိုက်ဖြတ်ပြီး email ကိုရှာကာ { user, created: false } ကို return ပြန်ရမယ်
  • တခြား error တိုင်းကို မပြောင်းဘဲ ပြန် throw လုပ်ရမယ်၊ ဒါမှ 422 ကို ဘယ်တော့မှ မဖုံးမိဘူး
  • Input တစ်ခုနဲ့ နှစ်ကြိမ်၊ မမှန်တဲ့ email နဲ့ တစ်ကြိမ် run ပြီး ရလဒ်တစ်ခုစီကို print လုပ်ပါ
ensure-user.mjs
// Make "create" safe to run twice.
// Assume createClient() from the lesson gives you client.createUser(input) and
// client.listUsers({ page, limit }), and that the ApiError class exists.

async function findByEmail(client, email) {
  // TODO 1: page through client.listUsers (limit 2) until you find the email
  // TODO 2: stop on an empty page or when page * limit >= meta.total; return null
}

async function ensureUser(client, input) {
  // TODO 3: try client.createUser(input) and return { user, created: true }
  // TODO 4: on ApiError status 409, call findByEmail and return { user, created: false }
  // TODO 5: rethrow every other error untouched (a 422 must NOT be swallowed)
}

// TODO 6: run ensureUser twice with the same input, plus once with a bad email,
//         and print what happened each time

ရလဒ်: Line လေးကြောင်းပါ။ ပထမအကြိမ်အတွက် created=true၊ ဒုတိယအကြိမ်နဲ့ ရှိပြီးသား user အတွက် created=false၊ နောက်ဆုံး line က ပြန် throw လုပ်ခဲ့တဲ့ 422 ApiError ကို ပြပါတယ်။

အရိပ်အမြွက် ကြည့်ရန်

Catch block ထဲမှာ err.status ကို နှိုင်းယှဉ်ပါ၊ listUsers က { data, meta } ပြန်တာကိုလည်း သတိရပါ။ Page ဗလာဖြစ်ရင် ဒါမှမဟုတ် page * limit က meta.total ရောက်ရင် paging ရပ်ပါ၊ မဟုတ်ရင် မရှိတဲ့ email က အဆုံးမရှိ loop ပတ်ပါလိမ့်မယ်။

အဖြေ ကြည့်ရန်
ensure-user.mjs
import http from "node:http";

// ===== A minimal mock: unique emails, JSON in, JSON out =====
const users = [
  { id: "u_1", name: "Alice", email: "alice@example.com" },
  { id: "u_2", name: "Bob", email: "bob@example.com" },
];
const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, "http://mock");
  const send = (status, body) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(body));
  };
  if (req.method === "GET" && url.pathname === "/v1/users") {
    const page = Number(url.searchParams.get("page") ?? 1);
    const limit = Number(url.searchParams.get("limit") ?? 10);
    const data = users.slice((page - 1) * limit, page * limit);
    return send(200, { data, meta: { page, limit, total: users.length } });
  }
  if (req.method === "POST" && url.pathname === "/v1/users") {
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const input = JSON.parse(raw);
    if (!input.email?.includes("@")) {
      return send(422, { error: { code: "VALIDATION_ERROR", message: "Invalid email" } });
    }
    if (users.some((u) => u.email === input.email)) {
      return send(409, { error: { code: "CONFLICT", message: "Email already in use" } });
    }
    const user = { id: `u_${users.length + 1}`, ...input };
    users.push(user);
    return send(201, { data: user });
  }
  send(404, { error: { code: "NOT_FOUND", message: "No such route" } });
});

// ===== A tiny client with the same ApiError shape as the project =====
class ApiError extends Error {
  constructor(status, code, message) {
    super(message);
    this.name = "ApiError";
    this.status = status;
    this.code = code;
  }
}

function createClient(baseUrl) {
  async function request(method, route, body) {
    const res = await fetch(`${baseUrl}${route}`, {
      method,
      headers: body ? { "Content-Type": "application/json" } : {},
      body: body && JSON.stringify(body),
    });
    const payload = await res.json();
    if (!res.ok) {
      const { code, message } = payload.error;
      throw new ApiError(res.status, code, message);
    }
    return payload;
  }
  return {
    createUser: async (input) => (await request("POST", "/users", input)).data,
    listUsers: ({ page = 1, limit = 10 } = {}) =>
      request("GET", `/users?page=${page}&limit=${limit}`),
  };
}

// ===== The challenge: make "create" safe to run twice =====
async function findByEmail(client, email) {
  for (let page = 1; ; page++) {
    const { data, meta } = await client.listUsers({ page, limit: 2 });
    const hit = data.find((u) => u.email === email);
    if (hit) return hit;
    if (data.length === 0 || page * 2 >= meta.total) return null;
  }
}

async function ensureUser(client, input) {
  try {
    return { user: await client.createUser(input), created: true };
  } catch (err) {
    if (!(err instanceof ApiError) || err.status !== 409) throw err;
    const existing = await findByEmail(client, input.email);
    if (!existing) throw err; // 409 but nobody found: do not hide a real conflict
    return { user: existing, created: false };
  }
}

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
try {
  const client = createClient(`http://127.0.0.1:${server.address().port}/v1`);
  const chidi = { name: "Chidi", email: "chidi@example.com" };
  for (const [label, input] of [
    ["first run ", chidi],
    ["second run", chidi],
    ["old friend", { name: "Bob", email: "bob@example.com" }],
  ]) {
    const { user, created } = await ensureUser(client, input);
    console.log(`${label}: created=${created} ${user.id} ${user.name}`);
  }
  try {
    await ensureUser(client, { name: "Nobody", email: "not-an-email" });
  } catch (err) {
    console.log(`bad input : ${err.name} ${err.status} ${err.code} (rethrown)`);
  }
} finally {
  server.close();
}

Quick Quiz 1 / 3

Server က DELETE /users/u_6 ကို 204 No Content နဲ့ ဖြေပါတယ်။ Client က အဲဒီ response ပေါ်မှာ res.json() ခေါ်ရင် ဘာဖြစ်မလဲ။

Quick Quiz 2 / 3

fetch ကို method POST နဲ့ body JSON.stringify({ name: "A" }) ပေးပြီး Content-Type header မပေးရင် fetch က ဘယ် Content-Type ကို ပို့မလဲ။

Quick Quiz 3 / 3

Demo မှာ ဒုတိယ delete u_6 က 404 NOT_FOUND ကို print လုပ်ပါတယ်။ User ပျောက်သွားဖို့ပဲ လိုတဲ့ script က ဘာကို နိဂုံးချုပ်သင့်လဲ။

မှတ်ထားရမယ့် အချက်များ

  • JSON body ကို ထင်ရှားတဲ့ Content-Type: application/json နဲ့ ပို့ပါ၊ fetch က string body ကို text/plain လို့ label ကပ်ပါတယ်
  • Parse မလုပ်ခင် 204 ကို စစ်ပါ၊ body မပါတဲ့ response ကို res.json() နဲ့ ဖတ်လို့မရလို့ပါ
  • ApiError မှာ error.fields ကို ထားပါ၊ ဒါမှ 422 က user ကို ဘယ် input ပြင်ရမလဲ ပြောနိုင်မယ်
  • တစ်စိတ်တစ်ပိုင်း ပြောင်းရင် PATCH သုံးပါ၊ POST ကို ထပ်ပို့ရင် record ဒုတိယတစ်ခု ဖြစ်နိုင်တာကိုလည်း မမေ့ပါနဲ့

OWASP API Security Project — OWASP

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Mini Project — Part 2: CRUD Feature ထည့်ခြင်း | Thuta Learning