ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
ဒါက လေ့ကျင့်ခန်းပါ၊ topic အသစ် မဟုတ်ပါဘူး။ အစိတ်အပိုင်းတွေကို သင်ကြိုက်ပြီးသားပါ၊ method၊ URL၊ header၊ optional body နဲ့ ပြန်လာတဲ့ status code တို့ပါ။ ဒီမှာ အဲဒါတွေကို ကိုယ်လက်ခံရရှိတာကို အတိအကျပြောပြတဲ့ local mock server တစ်ခုအောက်မှာ စုစည်းပါမယ်၊ ဒါကြောင့် ပို့ချင်ခဲ့တာနဲ့ wire ပေါ် တကယ်သွားတာကို နှိုင်းယှဉ်လို့ရပါတယ်။
Task တစ်ခုချင်းစီက သေးပါတယ်။ စာရွက်ပေါ်မှာ အရင်လုပ်၊ အဖြေကို ခန့်မှန်း၊ ပြီးမှ run ပါ၊ ခန့်မှန်းတဲ့ အကျင့်ကပဲ တကယ့် လေ့ကျင့်ခန်းပါ။
Problem → Why → Solution
ပြဿနာ: 200 တစ်ခုက အရာများများ မသက်သေပြဘူး
နမူနာ request တစ်ခု 200 ပြန်လာတာက အရာများများ မသက်သေပြပါဘူး။ Code တူတူက token ကို header မှားမှာ ပို့ထားနိုင်တယ်၊ server က တခြားအရာအဖြစ် decode လုပ်သွားမယ့် query string ကို တည်ဆောက်ထားနိုင်တယ်၊ JSON body ကို plain text လို label ကပ်ထားနိုင်တယ်၊ ဒါမှမဟုတ် ဗလာ list ကို error လို သဘောထားနိုင်ပါတယ်။ ဒီအမှားတွေက happy path ရဲ့ status ကိုပဲ ကြည့်ရင် မမြင်ရပါဘူး၊ နောက်မှ ရလဒ်မရှိတဲ့ user တစ်ယောက်၊ ဒါမှမဟုတ် production မှာပဲ ပေါ်တဲ့ 415 အဖြစ် ပေါ်လာပါတယ်။
// Gets a 200 from a lenient mock, and is still wrong in three ways
const q = "Alice & Bob";
const res = await fetch(`${base}/v1/users?q=${q}&limit=2`, { // the & splits the value
method: "POST", // a search should be GET
headers: { "X-API-Token": key }, // the header is X-API-Key
body: JSON.stringify({ name: "Alice" }), // goes out as text/plain
});
console.log(res.status);Status code ကို ယုံလို့ ဘာကြောင့် မရတာလဲ
Status code က server ဆုံးဖြတ်လိုက်တာကိုပဲ ပြောပြပါတယ်၊ သင်ပို့လိုက်တာကို မပြောပါဘူး။ Request ဖတ်ဖို့ လေ့ကျင့်ဖို့ ကျန်တစ်ဖက်ကို မြင်ရဖို့ လိုပါတယ်၊ request line နဲ့ လက်ခံခဲ့တဲ့ header တွေကို မှတ်တမ်းတင်တဲ့ server ပါ၊ ဒါမှ task တိုင်းက ခန့်မှန်းတာအစား wire ကို စစ်ဆေးတာနဲ့ အဆုံးသတ်ပါတယ်။
Core concept: request ဆိုတာ အပိုင်းခြောက်ခုပါတဲ့ စာချုပ်
ပို့တဲ့ request တိုင်းက အပိုင်းခြောက်ခုပါတဲ့ စာချုပ်သေးသေးလေးဖြစ်ပြီး လေ့ကျင့်ခန်းဆိုတာ အပိုင်းတစ်ခုချင်းစီကို သီးသန့်စစ်ဖို့ နည်းလမ်းပါ။ Table မှာ အပိုင်းတစ်ခုစီက ဘာကို ဆုံးဖြတ်လဲ၊ လူတွေ အများဆုံး လွဲတတ်တဲ့ အမှားက ဘာလဲ ပြထားပါတယ်။
| အပိုင်း | ဘာကို ဆုံးဖြတ်လဲ | အများဆုံး လွဲတတ်တာ |
|---|---|---|
| Method | Resource နဲ့ ဘာလုပ်ချင်လဲ | GET ဖြစ်ရမယ့်နေရာမှာ POST သုံးတာ၊ ဒါမှမဟုတ် ပြောင်းပြန် |
| URL | ဘယ် resource၊ query string နဲ့တကွ | Query value ထဲမှာ & ဒါမှမဟုတ် space ကို မ encode လုပ်တာ |
| Headers | သင်ဘယ်သူလဲ၊ ဘာပို့လဲ၊ ဘာလက်ခံလဲ | Header နာမည်မှား၊ ဒါမှမဟုတ် JSON body မှာ Content-Type မပါ |
| Body | Text အဖြစ် serialise လုပ်ထားတဲ့ data | JSON.stringify(object) အစား object ကို ပို့တာ |
| Authentication | Server က ဘယ် identity ကို သုံးမလဲ | API က key မျှော်နေတဲ့နေရာမှာ Bearer token ထည့်တာ |
| Response | Status အရင်၊ ပြီးမှ body | ဗလာ list ကို error အဖြစ် သဘောထားတာ |
Authentication မှာ ပုံစံ အသုံးများတာ နှစ်မျိုးရှိပါတယ်။ Bearer token က Authorization: Bearer <token> ထဲမှာ သွားပြီး user ဒါမှမဟုတ် app တစ်ခုကို ဖော်ပြတတ်ပြီး သက်တမ်းကုန်နိုင်ပါတယ်။ API key ကတော့ provider ရွေးတဲ့ နာမည်ရှိတဲ့ header ထဲက တည်ငြိမ်တဲ့ secret ပါ၊ ဥပမာ X-API-Key၊ ဒါကြောင့် အတိအကျ နာမည်ကို docs မှာ ဖတ်ပါ။ Header နာမည်တွေက အကြီးအသေး မခွဲပါဘူး၊ Authorization၊ authorization နဲ့ AUTHORIZATION က header တစ်ခုတည်းပါ၊ ဒါပေမယ့် key လို header value တွေက အကြီးအသေး ခွဲပါတယ်၊ lab-key နဲ့ LAB-KEY က မတူတဲ့ key တွေပါ။
Query string တွေကို encode လုပ်ရပါတယ်။ URL နဲ့ URLSearchParams class တွေက သင့်အတွက် လုပ်ပေးပါတယ်၊ space က + ဖြစ်ပြီး value ထဲက ampersand က %26 ဖြစ်လို့ parameter ကို နှစ်ခုအဖြစ် မခွဲမိစေပါဘူး။ Body မှာ အရာနှစ်ခု လိုပါတယ်၊ serialise လုပ်ထားတဲ့ data နဲ့ ဘယ်လိုဖတ်ရမလဲ ပြောတဲ့ Content-Type ပါ။ fetch က string body ကို default အနေနဲ့ text/plain;charset=UTF-8 လို့ label ကပ်လို့ JSON အတွက် application/json ကို ထင်ရှားစွာ ပေးရပါမယ်။
Response ကို အလွှာလိုက် ဖတ်ပါ၊ အဖြေတစ်ခုခု ရောက်ခဲ့လား (transport)၊ server က ဘာဆုံးဖြတ်လဲ (status)၊ body က parse ရလား မျှော်လင့်တာပါလား (content)။ ဗလာ list နဲ့ 200 က မှန်ကန်တဲ့ အဖြေပါ၊ 404 က 401 မဟုတ်ပါဘူး၊ body က JSON မဟုတ်တဲ့ 200 ဆိုရင် server ဒါမှမဟုတ် proxy ပျက်နေတာပါ။
- မပို့ခင် raw request ကို ခန့်မှန်း
- fetch နဲ့ ပို့
- Server မှတ်တမ်းတင်တာနဲ့ နှိုင်းယှဉ်
- Response ကို အလွှာသုံးထပ် ဖတ်
Status code က server ဆုံးဖြတ်တာကိုပဲ ပြောပါတယ်။ Server မှတ်တမ်းတင်တဲ့ request line ကို ကြည့်မှ သင် တကယ်ပို့ခဲ့တာကို သိရပါတယ်။
အခြေခံ ပုံစံ
const url = new URL("/v1/things", base);
url.searchParams.set("q", value); // encoding is done for you
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json", "X-API-Key": key },
body: JSON.stringify(payload),
});URL object က query value ကို encode လုပ်ပေးပြီး fetch က method၊ header၊ body ကို ယူပါတယ်၊ JSON body ဆိုရင် Content-Type ကို ထင်ရှားစွာ ရေးရပါတယ်။
Task 1 ကနေ 3 အထိ၊ server တကယ်မြင်တာနဲ့ အတူ
Lab server က Bearer token ဒါမှမဟုတ် X-API-Key ကို လက်ခံပြီး request line တိုင်းကို ရောက်လာတဲ့အတိုင်း မှတ်တမ်းတင်ပါတယ်။ လေ့ကျင့်ခန်းရဲ့ task တွေက အရင်လာပါတယ်၊ Bearer request နဲ့ သူ့ status၊ API key နဲ့ request တူတူ၊ JSON ထဲက field တစ်ခုကို ထုတ်ပြီး ဗလာ list အတွက် guard ထည့်တာပါ။ ပြီးတော့ wire ကို ဖတ်ဖို့ လေ့ကျင့်တဲ့ အပို check သုံးခုပါ၊ header အကြီးအသေး၊ query encoding နဲ့ Content-Type ပါ/မပါ ပို့တဲ့ JSON body ပါ။
Run မလုပ်ခင် print လုပ်မယ့် line တိုင်းအတွက် ခန့်မှန်းချက်ကို ရေးထားပါ။ သင့်ကို အံ့သြစေတဲ့ line တိုင်းက request တွေအကြောင်း သင့် mental model ထဲက ကွာဟချက်ပါ၊ ဒီ set ရှိတာ အဲဒါအတွက်ပါပဲ။
// Practice Set 1: the lab server records what it receives, so you can compare
// your request with what really went on the wire. Run: node lab.mjs
import http from "node:http";
// ===== Lab server (accepts a Bearer token OR an X-API-Key) =====
const BEARER = "lab-token";
const API_KEY = "lab-key";
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" },
];
const seen = []; // request lines exactly as they arrived, e.g. "GET /v1/users?limit=2"
function reply(res, status, body) {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
}
const problem = (code, message) => ({ error: { code, message } });
const lab = http.createServer(async (req, res) => {
seen.push(`${req.method} ${req.url}`);
const bearerOk = req.headers.authorization === `Bearer ${BEARER}`;
if (!bearerOk && req.headers["x-api-key"] !== API_KEY) {
return reply(res, 401, problem("UNAUTHORIZED", "Bad credentials"));
}
const url = new URL(req.url, "http://lab");
if (req.method === "GET" && url.pathname === "/v1/users") {
const q = (url.searchParams.get("q") ?? "").toLowerCase();
const limit = Number(url.searchParams.get("limit") ?? 10);
const data = users.filter((u) => u.name.toLowerCase().includes(q)).slice(0, limit);
return reply(res, 200, { data });
}
if (req.method === "POST" && url.pathname === "/v1/users") {
const type = req.headers["content-type"] ?? "(none)";
if (!type.startsWith("application/json")) {
return reply(res, 415, problem("UNSUPPORTED_MEDIA_TYPE", `Got ${type}`));
}
let raw = "";
for await (const chunk of req) raw += chunk;
let input;
try {
input = JSON.parse(raw);
} catch {
return reply(res, 400, problem("INVALID_JSON", "Body is not JSON"));
}
const user = { id: `u_${users.length + 1}`, name: input.name, email: input.email };
users.push(user);
return reply(res, 201, { data: user });
}
reply(res, 404, problem("NOT_FOUND", "No such route"));
});
// ===== The tasks =====
await new Promise((resolve) => lab.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${lab.address().port}`;
const bearer = { Authorization: `Bearer ${BEARER}` };
try {
// Task 1: Bearer token
const t1 = await fetch(`${base}/v1/users`, { headers: bearer });
console.log("task 1: status", t1.status);
// Task 2: the same request with an API key header instead
const t2 = await fetch(`${base}/v1/users`, { headers: { "X-API-Key": API_KEY } });
console.log("task 2: status", t2.status);
// Task 3: pull one field out of the JSON, then guard the empty list
const sample = { data: [{ id: "u_1", name: "Alice", email: "alice@example.com" }] };
console.log("task 3:", sample.data[0].email);
const empty = { data: [] };
console.log("task 3 on an empty list:", empty.data[0]?.email ?? "(no users)");
// Header names are case-insensitive; the key's value is not
const loud = await fetch(`${base}/v1/users`, { headers: { "X-API-KEY": API_KEY } });
const shout = await fetch(`${base}/v1/users`, { headers: { "x-api-key": "LAB-KEY" } });
console.log("header name case:", loud.status, "| key value case:", shout.status);
// Let URL encode the query string, then look at the wire
const url = new URL("/v1/users", base);
url.searchParams.set("q", "Alice & Bob");
url.searchParams.set("limit", "2");
const found = await (await fetch(url, { headers: bearer })).json();
console.log("on the wire:", seen.at(-1));
console.log("users found:", found.data.length, "(an empty list is still a 200)");
// A JSON body needs an explicit Content-Type
const post = (body, type) =>
fetch(`${base}/v1/users`, {
method: "POST",
headers: { ...bearer, ...(type && { "Content-Type": type }) },
body,
});
const person = JSON.stringify({ name: "Dara", email: "dara@example.com" });
const noType = await (await post(person)).json();
console.log("POST without Content-Type:", noType.error.code, "-", noType.error.message);
const good = await post(person, "application/json");
console.log("POST with the header:", good.status, (await good.json()).data.id);
const broken = await post("{name: Dara", "application/json");
console.log("POST with broken JSON:", broken.status, (await broken.json()).error.code);
} finally {
lab.close();
}Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- API key instead of Bearer
headers: { "X-API-Key": API_KEY }Task 2 က request တူတူကို Authorization အစား X-API-Key header နဲ့ ပို့ပါတယ်။ Lab server က နှစ်မျိုးလုံးကို လက်ခံလို့ status နှစ်ခုလုံး 200 ပါ၊ ကွာတာက header ပဲ ဖြစ်ပါတယ်။
- Let URL encode the query
url.searchParams.set("q", "Alice & Bob");Value ထဲက space နဲ့ & ကို လက်နဲ့ ရှောင်စရာ မလိုပါဘူး။ searchParams က + နဲ့ %26 အဖြစ် ပြောင်းပေးလို့ parameter က တစ်ခုတည်းအဖြစ် ကျန်ပါတယ်။
- Compare with the wire
seen.at(-1)seen ထဲမှာ server လက်ခံတဲ့ request line တိုင်းပါပြီး at(-1) က နောက်ဆုံးတစ်ခုပါ။ ဒါကို မိမိ ခန့်မှန်းချက်နဲ့ နှိုင်းယှဉ်တာက ဒီ lesson ရဲ့ အဓိက အကျင့်ပါ။
- Guard the empty list
empty.data[0]?.email ?? "(no users)"data[0].email က list ဗလာဆိုရင် TypeError ပေးပါတယ်။ ?. က undefined မှာ ရပ်ပြီး ?? က fallback စာသားပေးလို့ ဗလာ list က ပုံမှန် ရလဒ်အဖြစ် ကိုင်တွယ်ခံရပါတယ်။
- Content-Type is explicit
...(type && { "Content-Type": type }),post() helper က type ပေးမှသာ Content-Type ထည့်ပါတယ်။ ထည့်မထားရင် fetch က text/plain ကို ပို့လို့ server က 415 နဲ့ ငြင်းတာကို output ထဲမှာ တွေ့ရပါတယ်။
task 1: status 200
task 2: status 200
task 3: alice@example.com
task 3 on an empty list: (no users)
header name case: 200 | key value case: 401
on the wire: GET /v1/users?q=Alice+%26+Bob&limit=2
users found: 0 (an empty list is still a 200)
POST without Content-Type: UNSUPPORTED_MEDIA_TYPE - Got text/plain;charset=UTF-8
POST with the header: 201 u_4
POST with broken JSON: 400 INVALID_JSONTask တစ်ခုကို ဘယ်လို လုပ်ရမလဲ
၁။ ခန့်မှန်းပါ
မျှော်လင့်တဲ့ method၊ path၊ query string၊ header တွေနဲ့ ပြန်ရမယ့် status ကို ရေးထားပါ။
၂။ ပို့ပါ
Request ကို တကယ့် API မဟုတ်ဘဲ lab server ကို ပို့ပြီး run ပါ။
၃။ နှိုင်းယှဉ်ပါ
မှတ်တမ်းတင်ထားတဲ့ request line နဲ့ response ကို စစ်ပါ၊ ကွာခြားမှုတိုင်းက သင်ခန်းစာတစ်ခုပါ။
၄။ ပျက်အောင်လုပ်ကြည့်ပါ
အပိုင်းတစ်ခုကို ပြောင်းပါ (key မှား၊ header ဖြုတ်၊ JSON ချိုး) ပြီး run မလုပ်ခင် status အသစ်ကို ခန့်မှန်းပါ။
Token အစစ်နဲ့ ဘယ်တော့မှ မလေ့ကျင့်ပါနဲ့
ဒီမှာ task တိုင်းက lab-token နဲ့ lab-key ကို script ကြာချိန်လေးပဲ ရှိနေတဲ့ server တစ်ခုကို သုံးပါတယ်။ Token အစစ်ကို လေ့ကျင့်ခန်းထဲ ထည့်ရင် commit၊ log နဲ့ screenshot ထဲ ရောက်သွားနိုင်ပါတယ်။
Triage: response ကို ဖတ်ရမယ့် အစဉ်
| အလွှာ | မေးခွန်း | Failure ဥပမာ |
|---|---|---|
| Transport | အဖြေတစ်ခုခု ရောက်ခဲ့လား | ECONNREFUSED: ဘာမှ နားမထောင်နေ |
| Status | Server က ဘာဆုံးဖြတ်လဲ | 401၊ 404၊ 422 ဒါမှမဟုတ် 429၊ တစ်ခုချင်းစီ တုံ့ပြန်ပုံမတူ |
| Content | Body က parse ရလား၊ မျှော်တာနဲ့ ကိုက်လား | HTML ပါတဲ့ 200၊ ဒါမှမဟုတ် ဗလာ list ပါတဲ့ 200 |
ဒီအစဉ်က challenge ရဲ့ probe() function လုပ်တာနဲ့ အတိအကျ တူပါတယ်။ အလွှာတွေကို အဲဒီအစဉ်အတိုင်း ဖတ်ရင် သင့် code ရဲ့ branch တစ်ခုစီမှာ အလုပ်တစ်ခုပဲ ရှိပါတယ်။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
တကယ့် team တစ်ခုမှာ ဒီ task တွေက commit တိုင်း run တဲ့ test တွေ ဖြစ်လာပါတယ်၊ သိထားတဲ့ request တစ်ခုကို mock ဒါမှမဟုတ် sandbox ကို ပို့ပြီး status နဲ့ shape ကို assert လုပ်တဲ့ contract test နဲ့ key လဲပြီးနောက် authentication ဆက်အလုပ်လုပ်သေးလား စစ်တဲ့ smoke test တို့ပါ။ Customer က 'သင့် API က ဘာမှ မပြန်ဘူး' လို့ပြောတဲ့အခါ support engineer တွေလည်း လက်နဲ့ အလားတူလုပ်ပါတယ်၊ request အတိအကျကို ပြန်ဖန်တီး၊ server log နဲ့ နှိုင်းယှဉ်ပြီး header မှား၊ encode မလုပ်ထားတဲ့ character ဒါမှမဟုတ် customer ရဲ့ code က error လို သဘောထားတဲ့ ဗလာ list ကို များသောအားဖြင့် တွေ့ရပါတယ်။
Server မြင်တာကို မှတ်တမ်းတင်တဲ့ အကျင့်က production မှာလည်း တန်ဖိုးတူပါတယ်။ ကောင်းတဲ့ API တွေက request id ကို ပြန်ပေးပြီး ကောင်းတဲ့ client တွေက secret အားလုံး redact လုပ်ထားတဲ့ method၊ URL နဲ့ status ကို log လုပ်လို့ bug report ကို server ဘက် log line နဲ့ ကိုက်ညီအောင် လုပ်နိုင်ပါတယ်။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
Request ကို status တစ်ခုတည်းနဲ့ ဆုံးဖြတ်တာ
Server က လွယ်လွယ်လက်ခံရင် console.log(res.status) က key ကို နေရာမှားမှာ ပို့တဲ့ request နဲ့ ampersand မှာ query value ပြတ်သွားတဲ့ request အတွက်တောင် 200 ကို print လုပ်ပါတယ်။ Server လက်ခံခဲ့တာနဲ့ နှိုင်းယှဉ်ပြီး status အပြင် body ကိုပါ assert လုပ်ပါ။
Query string ကို လက်နဲ့ တည်ဆောက်တာ
q ကို Alice & Bob လို့ထားပြီး `?q=${q}` လို့ရေးရင် parameter နှစ်ခု ပို့ပြီး value တစ်ဝက်ကို တိတ်တိတ်လေး ဖယ်ပစ်ပါတယ်။ Value ကို encode လုပ်ပေးတဲ့ URL နဲ့ searchParams.set ကို သုံးပါ။
ဗလာဖြစ်နိုင်တဲ့ list ရဲ့ ပထမ element ကို တန်းညွှန်းတာ
List ဗလာဆိုရင် data[0].email က TypeError: Cannot read properties of undefined (reading 'email') ကို throw လုပ်ပါတယ်၊ ဗလာ list ကတော့ ပုံမှန်နဲ့ မှန်ကန်တဲ့ အဖြေပါ။ data.length ကို စစ်ပါ၊ ဒါမှမဟုတ် data[0]?.email ကို fallback နဲ့ သုံးပါ။
Mini challenge
Response triage function တစ်ခု ဆောက်ပါ
ရလဒ်ရှိသမျှကို { kind, detail } ဆုံးဖြတ်ချက်တစ်ခုအဖြစ် ပြောင်းပေးတဲ့ probe(url, init) ကို ရေးပါ၊ ဒါဆို program ကျန်တာက status code တွေကို ကစားစရာမလိုဘဲ kind ပေါ်မှာ switch လုပ်နိုင်ပါမယ်။ ပုံမှန် list၊ ဗလာ list၊ key မှား၊ မရှိတဲ့ user၊ မမှန်တဲ့ body၊ ကန့်သတ်ခံရတဲ့ request၊ 204၊ ပုံစံမမှန်တဲ့ body နဲ့ နောက်ဆုံး ဘာမှ နားမထောင်တဲ့ port တို့ကို ပြန်ပေးတဲ့ mock ကို ဆန့်ကျင်ပြီး run ပါ။
- Reject ဖြစ်တဲ့ fetch က err.cause.code ကနေ ဖတ်ထားတဲ့ တကယ့် code နဲ့ kind network ကို ပြန်ပေးရမယ်
- Body ကို text အဖြစ် အရင်ဖတ်ပြီး JSON.parse ကို try/catch ထဲမှာ လုပ်ပါ၊ parse မရတဲ့ text က bad_body ပါ
- 401၊ 404၊ 422 နဲ့ 429 ကို unauthorized၊ not_found၊ invalid နဲ့ rate_limited အဖြစ် အသုံးဝင်တဲ့ detail (error code၊ field နာမည်၊ Retry-After စက္ကန့်) နဲ့ map လုပ်ပါ
- 204 က no content နဲ့ ok ဖြစ်ပြီး ဗလာ data array ပါတဲ့ 2xx က error မဟုတ်ဘဲ empty ဖြစ်ရမယ်
// Response triage: turn ANY outcome into one { kind, detail } verdict.
// kinds: ok | empty | unauthorized | not_found | invalid | rate_limited
// | bad_body | http_error | network
async function probe(url, init = {}) {
// TODO 1: await fetch(url, init); if it rejects, return { kind: "network", detail }
// and read the real code from err.cause?.code instead of assuming one
// TODO 2: read the body with res.text() FIRST; a 204 or an empty 2xx body is "ok"
// TODO 3: JSON.parse the text inside try/catch; failure means { kind: "bad_body" }
// TODO 4: map 401, 404, 422 (list the field names), 429 (include Retry-After seconds)
// TODO 5: a 2xx whose data is an empty array is "empty", not an error
}
// TODO 6: point probe() at your own mock (or the lesson's lab server) for nine cases,
// including a closed port, and print one "label -> kind (detail)" line eachရလဒ်: label -> kind (detail) ပုံစံ line ကိုးကြောင်းထွက်ပြီး closed port -> network (ECONNREFUSED) နဲ့ ပြီးဆုံးပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
res.text() က ပုံမှန် body မှာ throw မလုပ်လို့ JSON.parse ကို ကိုယ်တိုင်ခေါ်ပြီး SyntaxError ကို catch လုပ်နိုင်ပါတယ်။ ပိတ်ထားတဲ့ port အတွက် server တစ်ခုဖန်တီး၊ သူ့ port ကိုဖတ်၊ ပိတ်ပြီး အဲဒီ port ကို fetch လုပ်ပါ။
အဖြေ ကြည့်ရန်
import http from "node:http";
const KEY = "lab-key";
const json = (res, status, body, headers = {}) => {
res.writeHead(status, { "Content-Type": "application/json", ...headers });
res.end(JSON.stringify(body));
};
// A mock that misbehaves in exactly the ways a real provider eventually will
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://mock");
if (req.headers["x-api-key"] !== KEY) {
return json(res, 401, { error: { code: "UNAUTHORIZED", message: "Bad key" } });
}
if (url.pathname === "/v1/users" && req.method === "GET") {
const q = url.searchParams.get("q");
const data = q ? [] : [{ id: "u_1" }, { id: "u_2" }, { id: "u_3" }];
return json(res, 200, { data });
}
if (url.pathname === "/v1/users/u_404") {
return json(res, 404, { error: { code: "NOT_FOUND", message: "No such user" } });
}
if (url.pathname === "/v1/users" && req.method === "POST") {
const fields = { name: "required", email: "invalid" };
const error = { code: "VALIDATION_ERROR", message: "Bad input", fields };
return json(res, 422, { error });
}
if (url.pathname === "/v1/users/u_1" && req.method === "DELETE") {
res.writeHead(204);
return res.end();
}
if (url.pathname === "/v1/burst") {
const body = { error: { code: "RATE_LIMITED", message: "Slow down" } };
return json(res, 429, body, { "Retry-After": "3" });
}
if (url.pathname === "/v1/garbled") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end("<html>maintenance</html>");
}
json(res, 404, { error: { code: "NOT_FOUND", message: "No such route" } });
});
// Turn ANY outcome into one { kind, detail } verdict
async function probe(url, init = {}) {
let res;
try {
res = await fetch(url, init);
} catch (err) {
return { kind: "network", detail: err.cause?.code ?? err.name };
}
const text = await res.text();
if (res.status === 204 || (res.ok && text === "")) {
return { kind: "ok", detail: "no content" };
}
let body;
try {
body = JSON.parse(text);
} catch {
return { kind: "bad_body", detail: `status ${res.status}` };
}
if (res.status === 401) return { kind: "unauthorized", detail: body.error.code };
if (res.status === 404) return { kind: "not_found", detail: body.error.code };
if (res.status === 422) {
return { kind: "invalid", detail: Object.keys(body.error.fields ?? {}).join(", ") };
}
if (res.status === 429) {
const seconds = Number(res.headers.get("retry-after") ?? 1);
return { kind: "rate_limited", detail: `retry in ${seconds}s` };
}
if (!res.ok) return { kind: "http_error", detail: `status ${res.status}` };
if (Array.isArray(body.data) && body.data.length === 0) {
return { kind: "empty", detail: "0 items" };
}
return { kind: "ok", detail: `${body.data?.length ?? 1} items` };
}
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
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}`;
await new Promise((resolve) => closed.close(resolve));
const auth = { headers: { "X-API-Key": KEY } };
const cases = [
["list", `${base}/v1/users`, auth],
["search nobody", `${base}/v1/users?q=zzz`, auth],
["wrong key", `${base}/v1/users`, { headers: { "X-API-Key": "nope" } }],
["missing user", `${base}/v1/users/u_404`, auth],
["invalid body", `${base}/v1/users`, { ...auth, method: "POST", body: "{}" }],
["too fast", `${base}/v1/burst`, auth],
["delete", `${base}/v1/users/u_1`, { ...auth, method: "DELETE" }],
["garbled", `${base}/v1/garbled`, auth],
["closed port", `${deadBase}/v1/users`, auth],
];
try {
for (const [label, url, init] of cases) {
const { kind, detail } = await probe(url, init);
console.log(`${label.padEnd(14)}-> ${kind} (${detail})`);
}
} finally {
server.close();
}Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Bearer token က Authorization ထဲ၊ API key က provider နာမည်ပေးတဲ့ header ထဲ ထည့်ပါ၊ header နာမည်က အကြီးအသေးမခွဲပေမယ့် value ကတော့ ခွဲပါတယ်
- Query value တွေကို string ဆက်တာအစား URL နဲ့ URLSearchParams ကို encode လုပ်ခိုင်းပါ
- JSON body မှာ Content-Type: application/json ကို ထင်ရှားစွာ ပေးရပါမယ်၊ fetch က string ကို text/plain လို့ label ကပ်လို့ပါ
- Response ကို အလွှာလိုက် (transport၊ status၊ content) ဖတ်ပြီး ဗလာ list ကို ပုံမှန်အောင်မြင်မှုအဖြစ် သဘောထားပါ
RFC 9110 — HTTP Semantics — IETF