ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Practice Set 1 က request တစ်ခုချင်းစီကို စစ်ခဲ့ပါတယ်။ ဒီ set က အဲဒါတွေကို ချိတ်ဆက်ပါတယ်၊ create၊ page လိုက် list၊ update၊ delete လုပ်ပြီး အဆင့်တိုင်းကို ကိုယ့် variable တွေကို ယုံတာအစား server ကို ပြန်မေးပြီး အတည်ပြုပါမယ်။ ထပ်ရတဲ့ skill က error flow ပါ၊ task တိုင်းအတွက် request ကို ပယ်ချခံရ၊ ကန့်သတ်ခံရ ဒါမှမဟုတ် လုံးဝ မရောက်တဲ့အခါ ဘာဖြစ်သင့်လဲ ဆုံးဖြတ်ရပါတယ်။
ဒိုင်ယာရီတစ်အုပ်ထဲ ရေးတာနဲ့ ဘဏ်စာအုပ်ကို သွားစစ်တာကို နှိုင်းယှဉ်ကြည့်ပါ။ ဒိုင်ယာရီက ကိုယ်ထင်တာကို ပြောပြီး ဘဏ်စာအုပ်ကပဲ တကယ်ဖြစ်တာကို ပြောပါတယ်။ ဒီ set ထဲမှာ ကိုယ့် variable တွေက ဒိုင်ယာရီ၊ server က ဘဏ်စာအုပ်ပါ။
Problem → Why → Solution
ပြဿနာ: demo data မှာပဲ အလုပ်လုပ်တဲ့ CRUD screen
Demo data မှာ အလုပ်လုပ်တဲ့ CRUD screen က အရာများများ မသက်သေပြပါဘူး။ ဒုတိယ page က ပထမ page ရဲ့ နောက်ဆုံး user ကို ထပ်ပြနေတာ၊ client က ကိုယ့် copy ကို ပြင်လို့သာ update သိမ်းထားသလို မြင်ရတာ၊ delete က record ကို list ထဲ ကျန်ခဲ့တာ၊ ကန့်သတ်ခံရတဲ့ request ကို တိတ်တိတ်လေး လွှတ်ပစ်တာတွေရှိနေတာတောင် အောင်မြင်နေနိုင်ပါတယ်။ ဒါတွေက request အသစ်နဲ့ စစ်ပြီး failure ကို ရည်ရွယ်ချက်ရှိရှိ ထည့်မှသာ ပေါ်ပါတယ်။
// "Passes" because it only ever trusts its own variables
const created = [];
for (const name of ["A", "B", "C"]) created.push(await createUser(name));
created[1].email = "b@new.example.com"; // edited the local copy, no PATCH was sent
created.splice(0, 1); // removed locally, no DELETE was sent
console.log(created.length === 2 ? "all good" : "broken"); // the server was never askedအတည်ပြုချက်က ဘယ်နေရာကို ဖြတ်ရမလဲ
အတည်ပြုချက်က တကယ့် user ဖြတ်ရတဲ့ နယ်နိမိတ်ကိုပဲ ဖြတ်ရပါမယ်။ Client ရဲ့ memory က system of record မဟုတ်ပါဘူး၊ server ပါ။ ဒါကြောင့် ဒီ set ထဲက mutation တိုင်းကို HTTP ပေါ်က ပြန်ဖတ်တဲ့ read တစ်ခု လိုက်ပြီး failure path တိုင်းကို ရည်ရွယ်ချက်ရှိရှိ ဖြစ်စေပါတယ်။
Core concept: state၊ invariant နဲ့ failure injection
အမှန်တကယ်ဆန်တဲ့ လေ့ကျင့်ခန်းက code ကနေမစဘဲ နောက်ပိုင်း မဖြစ်မနေ မှန်နေရမယ့် စည်းမျဉ်းတွေကနေ စပါတယ်။ အဲဒီ invariant တွေကို အရင်ရေး၊ ပြီးမှ call တွေကို တည်ဆောက်၊ ပြီးရင် ရည်ရွယ်ချက်ရှိရှိ ချိုးဖောက်ကြည့်ပါ။
၁။ Invariant တွေကို အရင်ရေးပါ
Create သုံးကြိမ်နဲ့ limit=2 ပြီးရင် page 1 မှာ user နှစ်ယောက်၊ page 2 မှာ တစ်ယောက်၊ meta.total က 3 ဖြစ်ပြီး page 3 က error မဟုတ်ဘဲ ဗလာ list ဖြစ်ရပါမယ်။ id တွေက မထပ်ဘဲ delete ပြီးနောက်လည်း ပြန်မသုံးပါဘူး။
၂။ ပြောင်းပြီး ပြန်ဖတ်ပါ
PATCH နဲ့ DELETE တိုင်းကို GET အသစ်တစ်ခု လိုက်ပါတယ်။ ပြောင်းတဲ့ call ရဲ့ response က server လက်ခံတာကို ပြောပြီး ပြန်ဖတ်တာကပဲ ဘာသိမ်းထားလဲ ပြောပါတယ်။
၃။ Failure ကို ရည်ရွယ်ချက်ရှိရှိ ထည့်ပါ
Task တိုင်းအတွက် client က 401၊ 404၊ 409၊ 422၊ 429 နဲ့ ပြတ်နေတဲ့ connection ကို ဘယ်လိုတုံ့ပြန်မလဲ ဆုံးဖြတ်ပြီး mock ကို ဆန့်ကျင်ပြီး တစ်ခုချင်းစီကို ဖြစ်စေပါ၊ ဒါမှ ဆုံးဖြတ်ချက်က မျှော်လင့်တာမဟုတ်ဘဲ test လုပ်ပြီးသားဖြစ်မယ်။
| Status ဒါမှမဟုတ် failure | Client ရဲ့ တုံ့ပြန်မှု | ပြန်ကြိုးစားမလား |
|---|---|---|
| 401 | ရပ်ပြီး token မှားနေပုံရတယ်လို့ user ကိုပြော | မလုပ်ဘူး |
| DELETE ပြီးနောက် 404 | အောင်မြင်၊ record က ဖျက်ပြီးသား | မလုပ်ဘူး |
| 409 | Item ကို ကျော်၊ ဒါမှမဟုတ် ရှိပြီးသား record ကို ရှာ | မလုပ်ဘူး |
| 422 | မှားတဲ့ field တွေကို user ကို report လုပ် | မလုပ်ဘူး |
| Retry-After ပါတဲ့ 429 | ပေးထားတဲ့ အချိန်စောင့်ပြီး request တူတူ ပြန်ပို့ | လုပ်၊ ကန့်သတ်ချက်နဲ့ |
| Connection refused | ရပ်ပြီး code ကို report၊ ဒါမှမဟုတ် backoff နဲ့ ပြန်ကြိုးစား | ဖြစ်နိုင် |
အစဉ်အတိုင်း အရေးကြီးရင် Promise.all မဟုတ်ဘဲ await ပါတဲ့ for...of loop နဲ့ user တွေကို create လုပ်ပါ။ Parallel request တွေက server ကို ဘယ်အစဉ်နဲ့မဆို ရောက်နိုင်လို့ id တွေနဲ့ page ခွဲဝေမှုက run တစ်ခုနဲ့တစ်ခု ကွာသွားပါလိမ့်မယ်။ Promise.all ကို အစဉ်ကို စိတ်မဝင်စားတဲ့ ကိုယ်စီ လွတ်လပ်တဲ့ request တွေအတွက်ပဲ သုံးပါ။
Pagination မှာလည်း ကိုယ်ပိုင် invariant တွေ ရှိပါတယ်။ Page နံပါတ်က 1 ကနေစပြီး နောက်ဆုံး page က တိုနိုင်ပါတယ်၊ အဆုံးကျော်တဲ့ page က error မဟုတ်ဘဲ ဗလာ list ဖြစ်ပြီး page တွေကို လျှောက်တဲ့ loop က meta.total မှာရော ဗလာ page မှာပါ ရပ်သင့်ပါတယ်၊ ဒါမှ total မှားနေလည်း အဆုံးမရှိ loop မဖြစ်ပါဘူး။
- နောက်ပိုင်း ဘာမှန်ရမလဲ ဖော်ပြ
- Call ကို လုပ်
- HTTP ပေါ်က ပြန်ဖတ်
- ရည်ရွယ်ချက်နဲ့ ဖျက်ပြီး ပြန် assert
သင့် variable တွေက ဖြစ်စေချင်ခဲ့တာကို ဖော်ပြပါတယ်။ Request အသစ်ကပဲ server က တကယ်သိမ်းထားတာကို ဖော်ပြပါတယ်။
အခြေခံ ပုံစံ
await mutate(); // POST / PATCH / DELETE
const after = await readBack(); // a fresh GET, never local state
assertEqual(after, expected);
queueFault(status); // refuse, throttle or drop ONE request
const outcome = await attempt(mutate);
assertEqual(outcome.kind, expectedKind);Mutation တိုင်းကို ပြန်ဖတ်တဲ့ read နဲ့ assert တစ်ခု လိုက်ပါတယ်၊ ပြီးတော့ failure တစ်ခုကို queue ထဲထည့်ပြီး client ရဲ့ တုံ့ပြန်ပုံကို assert ထပ်လုပ်ပါတယ်။
Task 1 ကနေ 4 အထိ၊ ပြန်ဖတ်ပြီး အတည်ပြုထားတာ
Mock API က ဗလာကနေ စတာမို့ file ရဲ့ ပထမလုပ်တာက ဗလာ collection ကို list လုပ်တာပါ၊ client အများစု မေ့တတ်တဲ့ case ပါ။ ပြီးတော့ set ရဲ့ task လေးခုကို အစဉ်လိုက် ဖြေရှင်းပါတယ်၊ create သုံးခုပြီး page နှစ်ခုနဲ့ ဗလာဖြစ်တဲ့ တတိယ page၊ GET နဲ့ အတည်ပြုတဲ့ PATCH၊ 404 နဲ့ အတည်ပြုတဲ့ DELETE နဲ့ token မှားတာကို ဖော်ရွေတဲ့ စာကြောင်းတစ်ကြောင်းအဖြစ် ပြောင်းတာပါ။
call() helper သေးသေးလေးက HTTP error မှာ ဘယ်တော့မှ throw မလုပ်ဘဲ { status, body } ကို ပြန်ပေးပါတယ်။ ဒါကြောင့် 404 ဒါမှမဟုတ် 401 ကို ပုံမှန်ရလဒ်အဖြစ် assert လုပ်ရ လွယ်ပါတယ်။ Run မလုပ်ခင် print လုပ်မယ့် line တစ်ကြောင်းချင်းစီကို ခန့်မှန်းပါ။
// Practice Set 2: create, page, update, delete and fail, verified by re-reading.
// Run: node lifecycle.mjs (the mock API lives in this file)
import http from "node:http";
// ===== Mock API: starts EMPTY, so the empty list is a real case =====
const GOOD = "good-token";
const users = [];
let nextId = 1;
function reply(res, status, body) {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(body === undefined ? undefined : JSON.stringify(body));
}
const problem = (code, message) => ({ error: { code, message } });
async function readBody(req) {
let raw = "";
for await (const chunk of req) raw += chunk;
return JSON.parse(raw);
}
const mock = http.createServer(async (req, res) => {
if (req.headers.authorization !== `Bearer ${GOOD}`) {
return reply(res, 401, problem("UNAUTHORIZED", "Bad token"));
}
const url = new URL(req.url, "http://mock");
const id = url.pathname.split("/")[3]; // /v1/users/:id
const user = users.find((u) => u.id === id);
if (req.method === "GET" && !id) {
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 reply(res, 200, { data, meta: { page, limit, total: users.length } });
}
if (req.method === "POST" && !id) {
const created = { id: `u_${nextId++}`, ...(await readBody(req)) };
users.push(created);
return reply(res, 201, { data: created });
}
if (id && !user) return reply(res, 404, problem("NOT_FOUND", `No user ${id}`));
if (req.method === "GET") return reply(res, 200, { data: user });
if (req.method === "PATCH") {
Object.assign(user, await readBody(req));
return reply(res, 200, { data: user });
}
if (req.method === "DELETE") {
users.splice(users.indexOf(user), 1);
return reply(res, 204);
}
reply(res, 405, problem("METHOD_NOT_ALLOWED", req.method));
});
// ===== A tiny helper: never throws on HTTP errors, returns { status, body } =====
async function call(base, method, path, { body, token = GOOD } = {}) {
const res = await fetch(`${base}${path}`, {
method,
headers: {
Authorization: `Bearer ${token}`,
...(body && { "Content-Type": "application/json" }),
},
body: body && JSON.stringify(body),
});
const text = await res.text();
return { status: res.status, body: text ? JSON.parse(text) : null };
}
const names = (r) => r.body.data.map((u) => u.name).join(", ") || "(empty)";
await new Promise((resolve) => mock.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${mock.address().port}/v1`;
const get = (path, token) => call(base, "GET", path, { token });
try {
const first = await get("/users");
console.log("empty list: total =", first.body.meta.total);
// Task 1: create three users IN ORDER, then page through them
for (const letter of ["A", "B", "C"]) {
const email = `${letter.toLowerCase()}@example.com`;
await call(base, "POST", "/users", { body: { name: letter, email } });
}
const pages = [];
for (const page of [1, 2, 3]) pages.push(await get(`/users?page=${page}&limit=2`));
console.log("task 1:", pages.map((p, i) => `page ${i + 1} = ${names(p)}`).join(" | "));
console.log("task 1: total =", pages[1].body.meta.total);
// Task 2: PATCH one user, then prove it with a fresh GET
const change = { email: "b@new.example.com" };
const patched = await call(base, "PATCH", "/users/u_2", { body: change });
const reread = await get("/users/u_2");
console.log(`task 2: ${patched.status} ${patched.body.data.email}`);
console.log("task 2: GET confirms", reread.body.data.email);
// Task 3: DELETE, then expect a 404 (not a failure!) when reading it back
const removed = await call(base, "DELETE", "/users/u_2");
const gone = await get("/users/u_2");
const after = `GET ${gone.status} ${gone.body.error.code}`;
console.log(`task 3: DELETE ${removed.status} | ${after}`);
console.log("task 3: left =", names(await get("/users")));
// Task 4: a wrong token becomes a friendly sentence
const denied = await get("/users", "wrong");
const friendly = "That token looks wrong - please double-check it.";
console.log("task 4:", denied.status, "->", denied.status === 401 ? friendly : "ok");
} finally {
mock.close();
}Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Sequential creates
for (const letter of ["A", "B", "C"]) {await ပါတဲ့ ရိုးရိုး for...of loop က user တွေကို A၊ B၊ C အစဉ်အတိုင်း ဖန်တီးလို့ id တွေက u_1၊ u_2၊ u_3 အဖြစ် run တိုင်း တူပါတယ်။
- Page 3 is empty, not an error
pages.push(await get(`/users?page=${page}&limit=2`))Page သုံးခုလုံးကို တောင်းပါတယ်။ page 3 က အဆုံးကျော်လို့ 404 မဟုတ်ဘဲ data ဗလာနဲ့ 200 ပြန်လာတာကို (empty) အဖြစ် print ထုတ်တာ မြင်ရပါလိမ့်မယ်။
- Re-read after PATCH
const reread = await get("/users/u_2");PATCH response က server လက်ခံတာကို ပြောပါတယ်။ ဒီ GET အသစ်ကပဲ ပြောင်းထားတဲ့ email ကို တကယ်သိမ်းထားကြောင်း သက်သေပြတာပါ။
- A 404 after DELETE is the goal
const gone = await get("/users/u_2");ဖျက်ပြီးနောက် ဒီ GET က 404 NOT_FOUND ပြန်ရမယ်။ အဲဒါ ပျက်စီးမှု မဟုတ်ဘဲ delete အလုပ်လုပ်ကြောင်း သက်သေပါ။
- Helper returns statuses as data
return { status: res.status, body: text ? JSON.parse(text) : null };call() က error status တွေကို throw မလုပ်ဘဲ data အဖြစ် ပြန်ပေးပါတယ်။ Body မရှိတဲ့ 204 အတွက်လည်း null ပေးလို့ parse အမှား မဖြစ်ပါဘူး။
empty list: total = 0
task 1: page 1 = A, B | page 2 = C | page 3 = (empty)
task 1: total = 3
task 2: 200 b@new.example.com
task 2: GET confirms b@new.example.com
task 3: DELETE 204 | GET 404 NOT_FOUND
task 3: left = A, C
task 4: 401 -> That token looks wrong - please double-check it.စမ်းသပ်သင့်တဲ့ pagination edge case တွေ
Pagination bug တွေက နယ်စပ်မှာ ပုန်းနေတတ်ပါတယ်။ အောက်က table က collection ရဲ့ အရွယ်အစားအလိုက် client က မျှော်လင့်ရမယ့် အရာကို ပြထားပါတယ်။ Example က ပထမ၊ တတိယနဲ့ (page 3 ကတဆင့်) စတုတ္ထ row ကို ဖုံးပါတယ်၊ ကျန်တာတွေကိုတော့ ကိုယ့် test တွေက ဖုံးသင့်ပါတယ်။
| Case | Request | မျှော်လင့်ချက် |
|---|---|---|
| Collection ဗလာ | GET /users | 200၊ data ဗလာ၊ meta.total က 0 |
| အတိအကျ စားလို့ပြတ် | User 4 ယောက်၊ limit=2 | ပြည့်တဲ့ page နှစ်ခု၊ page 3 ဗလာ |
| နောက်ဆုံး page တို | User 3 ယောက်၊ limit=2 | Page 2 မှာ user တစ်ယောက် |
| အဆုံးကျော် | page=99 | 404 မဟုတ်ဘဲ ဗလာ list နဲ့ 200 |
| limit မမှန် | limit=0 ဒါမှမဟုတ် limit=-1 | Server ဆုံးဖြတ်: ကန့်သတ် ဒါမှမဟုတ် 4xx၊ docs ဖတ်ပါ |
Code မရေးခင် failure plan ကို ရေးပါ
Failure plan ဆိုတာ code မရေးခင် ဖြည့်တဲ့ table ပါ၊ call တစ်ခုချင်းစီအတွက် ဘယ် status တွေ ပြန်လာနိုင်လဲ၊ client က တစ်ခုချင်းစီမှာ ဘာလုပ်မလဲပါ။ အရင်ရေးခြင်းက ဘုံအမှားနှစ်ခုကို တားပါတယ်၊ အမြဲတမ်း အတူတူပဲ ကျရှုံးမယ့် 422 ကို ပြန်ကြိုးစားတာနဲ့ ပျက်နေတဲ့ credential ကို ဗလာ screen နောက်ကွယ်မှာ ဖုံးထားမယ့် 401 ကို မျိုချထားတာပါ။
ထပ်ပို့လို့ မပြေလည်တာကို ပြန်မကြိုးစားပါနဲ့
422 ဒါမှမဟုတ် 401 က အချိန်တိုင်း အဖြေတူတူ ပြန်ပေးတာမို့ ပြန်ကြိုးစားတာက error message ကို နှောင့်နှေးစေရုံပါပဲ။ Retry ကို 429၊ timeout နဲ့ ယာယီ 5xx အတွက် သီးသန့်ထားပါ။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
ဒီ chain က integration test suite အားလုံးလိုလို ရဲ့ အရိုးစုပါ၊ fixture ဖန်တီး၊ endpoint ကို လေ့ကျင့်၊ ပြန်ဖတ်၊ ရှင်းလင်းပြီး မပျော်ရွှင်တဲ့ လမ်းကြောင်းတွေအတွက် fault matrix ပါပါတယ်။ Team တွေက CI မှာ sandbox ဒါမှမဟုတ် mock server ကို ဆန့်ကျင်ပြီး run ပါတယ်၊ 'ဒီမှာ 429 ထည့်' အဆင့်က ပုံမှန်အားဖြင့် လက်နဲ့ test လုပ်ရင် ဘယ်သူမှ သတိမထားမိတဲ့ bug ကို တွေ့တတ်ပါတယ်၊ developer က ဖြည်းဖြည်းနှိပ်ကြည့်တဲ့အခါ rate limit မပေါ်လို့ပါ။
Challenge မှာ ဆောက်မယ့် bulk import တွေက နေရာတိုင်းမှာ ရှိပါတယ်၊ customer ရဲ့ contact list ကို onboarding လုပ်၊ system တစ်ခုကနေ တစ်ခုဆီ user ရွှေ့၊ spreadsheet ကို sync လုပ်တာတွေပါ။ သူတို့ရဲ့ အဓိက လိုအပ်ချက်က report ပါ။ Operator တွေက ဘယ် row တွေ create ဖြစ်လဲ၊ ဘယ်တွေ duplicate အဖြစ် ကျော်လဲ၊ ဘယ်တွေ ဘာကြောင့် ပယ်ချခံရလဲ အတိအကျ သိဖို့ လိုလို့ data ကိုပြင်ပြီး အလုပ်တစ်ခုလုံးကို ပြန်မလုပ်ဘဲ ထပ် run နိုင်ပါတယ်။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
Local variable တွေနဲ့ အတည်ပြုတာ
POST က ပြန်ရတဲ့ object ကို ပြင်ပြီး အဲဒါကို assert လုပ်တာက server အကြောင်း ဘာမှ မသက်သေပြပါဘူး။ Mutation တိုင်းပြီးနောက် GET အသစ်တစ်ခုလုပ်ပြီး အဲဒါကို assert လုပ်ပါ။
Promise.all နဲ့ အစဉ်ကို ယူဆတာ
Create သုံးခုကို parallel ပစ်လိုက်ရင် server ကို ဘယ်အစဉ်နဲ့မဆို ရောက်နိုင်လို့ id၊ page ထဲက အကြောင်းအရာနဲ့ total က run တစ်ခုနဲ့တစ်ခု ကွာပါတယ်။ အစဉ်အရေးကြီးရင် အစဉ်လိုက် loop သုံးပါ။
DELETE ပြီးနောက် 404 ကို bug လို သဘောထားတာ
404 က delete အလုပ်လုပ်တဲ့ သက်သေပါ။ အဲဒါကို assert လုပ်ပါ၊ record ပျောက်ဖို့ပဲ လိုတဲ့ script မှာလည်း DELETE ပေါ်က 404 ကို အောင်မြင်မှုအဖြစ် သဘောထားပါ။
429 ကို အဆုံးမရှိ ပြန်ကြိုးစားတာ ဒါမှမဟုတ် Retry-After ကို လျစ်လျူရှုတာ
Retry ကန့်သတ်ချက်မရှိရင် အမြဲကန့်သတ်ခံရတာက import ကို ရပ်စေပြီး header ကို လျစ်လျူရှုရင် server ကို ချက်ချင်း ထပ်ထိုးနှက်ပါတယ်။ ကြေညာထားတဲ့ အချိန်ကို စောင့်ပြီး အကြိမ်အနည်းငယ်နောက် လက်လျှော့ပါ။
Mini challenge
Report ပါတဲ့ bulk import တစ်ခု ဆောက်ပါ
item တိုင်းကို အစဉ်လိုက် POST လုပ်ပြီး မျှော်လင့်ထားတဲ့ failure အတွက် ဘယ်တော့မှ throw မလုပ်တဲ့ importUsers(baseUrl, items, { sleep, maxRetries }) ကို ရေးပါ။ created၊ skipped (409)၊ rejected (422၊ မှားတဲ့ field နာမည်ပါ) နဲ့ aborted (ဘာမှ မရောက်နိုင်တဲ့အခါ သတ်မှတ်) ပါတဲ့ report ကို ပြန်ပေးပါ။ 429 က Retry-After အချိန်စောင့်ပြီး item တူတူကို ပြန်ပို့ရပါမယ်။ ပြီးရင် limit=2 နဲ့ page တွေကို လျှောက်ဖတ်ပြီး နာမည်တိုင်းကို print လုပ်ပါ။
- Item တွေကို Promise.all မဟုတ်ဘဲ for...of နဲ့ await ကို သုံးပြီး တစ်ခုပြီးတစ်ခု ပို့ပါ
- 201 က created၊ 409 က skipped၊ 422 က မှားတဲ့ field နာမည်နဲ့ rejected ဆီ သွားရမယ်
- 429 က ထည့်ပေးထားတဲ့ sleep နဲ့ Retry-After စက္ကန့်စောင့်ပြီး item တူတူကို အများဆုံး maxRetries ကြိမ် ပြန်ပို့ရမယ်
- Reject ဖြစ်တဲ့ fetch (ဘယ်သူမှ နားမထောင်) က report.aborted ကို တကယ့် error code နဲ့ သတ်မှတ်ပြီး import ကို ရပ်ရမယ်
- ဗလာ items array က ဗလာ report ပြန်ပေးပြီး listAll က ဗလာ page မှာ ဒါမှမဟုတ် meta.total မှာ ရပ်ရမယ်
// Bulk import that survives refusals.
// Use the mock server from the lesson example, or write your own.
async function importUsers(baseUrl, items, { sleep, maxRetries = 2 } = {}) {
const report = { created: [], skipped: [], rejected: [], aborted: null };
// TODO 1: POST each item in ORDER (for...of with await, not Promise.all)
// TODO 2: 201 -> created, 409 -> skipped, 422 -> rejected (name the bad fields)
// TODO 3: 429 -> wait Retry-After seconds with sleep(ms) and resend the SAME item,
// at most maxRetries times
// TODO 4: fetch rejects (nobody listening) -> report.aborted = the error code, stop
return report;
}
async function listAll(baseUrl, pageSize) {
// TODO 5: walk page=1,2,... until a page is empty or page * pageSize >= meta.total
}
// TODO 6: import five items (new, duplicate, throttled, invalid, new), then listAll,
// then try an empty array and a closed portရလဒ်: Line ခုနစ်ကြောင်းပါ။ Item ငါးခုအတွက် created၊ skipped၊ rejected line တွေနဲ့ 2000 ms sleep တစ်ခုတည်း မှတ်တမ်းတင်တာ၊ page နှစ်ခုပေါ်က နာမည်လေးခု၊ ဗလာ input အတွက် ဗလာ report နဲ့ ပြတ်နေတဲ့ server အတွက် ECONNREFUSED တို့ပါ။
အရိပ်အမြွက် ကြည့်ရန်
Item တစ်ခုစီထဲမှာ attempt counter ပါတဲ့ for loop သုံးပြီး 429 ပြီးနောက် continue လုပ်ပါ။ Code ကို err.cause?.code နဲ့ ဖတ်ပါ။ listAll အတွက် page * pageSize ကို meta.total နဲ့ နှိုင်းယှဉ်ပြီး ဒုတိယ guard အဖြစ် ဗလာ page မှာလည်း ရပ်ပါ။
အဖြေ ကြည့်ရန်
import http from "node:http";
// ===== Mock API: one existing user, a duplicate check, and one throttled POST =====
const users = [{ id: "u_1", name: "Alice", email: "alice@example.com" }];
let nextId = 2;
let postsSeen = 0;
function reply(res, status, body, headers = {}) {
res.writeHead(status, { "Content-Type": "application/json", ...headers });
res.end(JSON.stringify(body));
}
const problem = (code, message, fields) => ({ error: { code, message, fields } });
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, "http://mock");
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 reply(res, 200, { data, meta: { page, limit, total: users.length } });
}
if (req.method === "POST" && url.pathname === "/v1/users") {
postsSeen++;
let raw = "";
for await (const chunk of req) raw += chunk;
const input = JSON.parse(raw);
if (postsSeen === 3) { // the third POST is throttled, once
const error = problem("RATE_LIMITED", "Slow down");
return reply(res, 429, error, { "Retry-After": "2" });
}
const fields = {};
if (!input.name) fields.name = "required";
if (!/^[^@\s]+@[^@\s]+$/.test(input.email ?? "")) fields.email = "invalid";
if (Object.keys(fields).length) {
return reply(res, 422, problem("VALIDATION_ERROR", "Invalid user", fields));
}
if (users.some((u) => u.email === input.email)) {
return reply(res, 409, problem("CONFLICT", "Email already in use"));
}
const user = { id: `u_${nextId++}`, ...input };
users.push(user);
return reply(res, 201, { data: user });
}
reply(res, 404, problem("NOT_FOUND", "No such route"));
});
// ===== The importer: one report, no exceptions for expected failures =====
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function importUsers(baseUrl, items, { sleep = wait, maxRetries = 2 } = {}) {
const report = { created: [], skipped: [], rejected: [], aborted: null };
for (const item of items) {
for (let attempt = 0; ; attempt++) {
let res;
try {
res = await fetch(`${baseUrl}/users`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(item),
});
} catch (err) {
report.aborted = err.cause?.code ?? "NETWORK_ERROR"; // nobody to talk to: stop
return report;
}
if (res.status === 429 && attempt < maxRetries) {
await sleep(Number(res.headers.get("retry-after") ?? 1) * 1000);
continue; // same item, one more try
}
const body = await res.json().catch(() => null);
if (res.status === 201) report.created.push(item.email);
else if (res.status === 409) report.skipped.push(item.email);
else if (res.status === 422) {
const fields = Object.keys(body.error.fields).join("+");
report.rejected.push(`${item.email || "(blank)"} [${fields}]`);
} else {
report.aborted = `HTTP ${res.status}`;
return report;
}
break;
}
}
return report;
}
async function listAll(baseUrl, pageSize) {
const names = [];
for (let page = 1; ; page++) {
const res = await fetch(`${baseUrl}/users?page=${page}&limit=${pageSize}`);
const { data, meta } = await res.json();
names.push(...data.map((u) => u.name));
if (data.length === 0 || page * pageSize >= meta.total) return { names, pages: page };
}
}
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}/v1`;
const closed = http.createServer();
await new Promise((resolve) => closed.listen(0, "127.0.0.1", resolve));
const deadBase = `http://127.0.0.1:${closed.address().port}/v1`;
await new Promise((resolve) => closed.close(resolve));
try {
const sleeps = [];
const items = [
{ name: "Fiona", email: "fiona@example.com" },
{ name: "Alice again", email: "alice@example.com" },
{ name: "Gus", email: "gus@example.com" },
{ name: "", email: "nope" },
{ name: "Hana", email: "hana@example.com" },
];
const report = await importUsers(base, items, { sleep: async (ms) => sleeps.push(ms) });
console.log("created: ", report.created.join(", "));
console.log("skipped: ", report.skipped.join(", "));
console.log("rejected:", report.rejected.join(", "));
console.log("aborted: ", report.aborted, "| sleeps:", sleeps.join(", "));
const all = await listAll(base, 2);
console.log(`server now has: ${all.names.join(", ")} (${all.pages} pages of 2)`);
const nothing = await importUsers(base, []);
console.log("empty input:", JSON.stringify(nothing));
const dead = await importUsers(deadBase, items.slice(0, 1));
console.log("dead server:", dead.aborted, "| created:", dead.created.length);
} finally {
server.close();
}Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Invariant တွေကို အရင်ရေးပြီး mutation တိုင်းကို local variable မဟုတ်ဘဲ GET အသစ်နဲ့ အတည်ပြုပါ
- အစဉ်အရေးကြီးရင် အစဉ်လိုက် loop နဲ့ create လုပ်ပြီး ဗလာ list၊ တိုတဲ့ နောက်ဆုံး page နဲ့ အဆုံးကျော်တဲ့ ဗလာ page ကို test လုပ်ပါ
- DELETE ပြီးနောက် 404 က delete အလုပ်လုပ်ကြောင်း သက်သေပါ၊ 401 နဲ့ 422 ကို ပြန်မကြိုးစားရဘဲ 429 က Retry-After ကို စောင့်ပါ
- Bulk operation က ပထမ failure မှာ throw မလုပ်ဘဲ created၊ skipped၊ rejected၊ aborted item တွေရဲ့ report ကို ပြန်ပေးသင့်ပါတယ်
OWASP API Security Project — OWASP