Thuta Learning
JavaScript
AdvancedProgrammingအခြေခံ

REST API Integration

JavaScriptသင်ခန်းစာ 3840 မိနစ်

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

  • /users နဲ့ /users/:id လို resource URL တွေကို GET, POST, PATCH, PUT, DELETE နဲ့ တွဲပြီး CRUD လုပ်နိုင်ဖို့
  • 200, 201, 204, 404 စတဲ့ status code တွေကို လုပ်ငန်းတစ်ခုချင်းစီအတွက် ခန့်မှန်းနိုင်ဖို့
  • ဘယ် method တွေက idempotent ဖြစ်လဲ ရှင်းပြပြီး POST ကို retry လုပ်ဖို့ idempotency key သုံးနိုင်ဖို့
  • page နဲ့ limit query parameter ပါတဲ့ list endpoint ကို စာမျက်နှာ အားလုံး ဖတ်နိုင်ဖို့

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

REST ကို ရိုးရိုးလေး ပြောရရင်

REST ဆိုတာ API ကို ဒီဇိုင်းဆွဲတဲ့ ပုံစံတစ်ခုပါ။ Server ပေါ်က အရာတိုင်း (user, order, product) ကို resource တစ်ခုအဖြစ် မြင်ပြီး URL တစ်ခုစီ ပေးထားပါတယ်: /users က user အားလုံး၊ /users/7 က user နံပါတ် 7။ ဘာလုပ်ချင်လဲဆိုတာကိုတော့ URL ထဲမှာ မရေးဘဲ HTTP method နဲ့ ပြောပါတယ်: GET က ဖတ်၊ POST က အသစ်ဖန်တီး၊ PATCH က ပြင်၊ DELETE က ဖျက်။

စာကြည့်တိုက်ကို စဉ်းစားကြည့်ပါ။ စာအုပ်တိုင်းမှာ စင်နံပါတ် (URL) ရှိပြီး ကောင်တာမှာ လုပ်လို့ရတာ အနည်းငယ်ပဲ ရှိပါတယ်: ကြည့်မယ်၊ အသစ်ထည့်မယ်၊ ပြင်မယ်၊ ပြန်ထုတ်မယ်။ Verb အရေအတွက် နည်းပြီး ပုံသေဖြစ်လို့ API အသစ်တစ်ခုကို တွေ့တဲ့အခါတောင် ဘယ်လို သုံးရမလဲ အလွယ်တကူ ခန့်မှန်းနိုင်ပါတယ်။

Problem → Why → Solution

ပြဿနာ: retry လုပ်လိုက်တော့ order နှစ်ခု ဖြစ်သွားတယ်

Checkout button နှိပ်လိုက်တော့ POST /orders request က server ဆီ ရောက်ပြီး order ကို သိမ်းလိုက်ပါတယ်၊ ဒါပေမဲ့ response ပြန်လာရင်း mobile connection ပြတ်သွားပါတယ်။ Client ကတော့ network error ကိုပဲ မြင်ပြီး 'fail ဖြစ်သွားတယ်' လို့ ထင်ကာ အလိုအလျောက် ထပ်ပို့ပါတယ်။ ရလဒ်က customer က order နှစ်ခုအတွက် ငွေနှစ်ခါ ပေးရတာပါပဲ။

blind-retry.js
async function placeOrder(cart) {
  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      const response = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(cart),
      });
      return await response.json();
    } catch {
      // "it failed" - but the server may already have saved the order
    }
  }
}

POST က ဘာကြောင့် retry လုပ်ရ မလုံခြုံတာလဲ

Network error က 'server ဆီ မရောက်ခဲ့ဘူး' လို့ အဓိပ္ပာယ် မရပါဘူး၊ 'response မရခဲ့ဘူး' လို့ပဲ အဓိပ္ပာယ်ရပါတယ်။ GET, PUT, DELETE က idempotent ဖြစ်လို့ နှစ်ခါ ပို့လည်း ရလဒ် တူတူပါပဲ။ POST ကတော့ ပို့တိုင်း resource အသစ် ဖန်တီးပါတယ်။ Server က Idempotency-Key header ကို ထောက်ပံ့ရင် retry တိုင်းမှာ key တူတူကို ပို့ပြီး server က ဒုတိယအကြိမ်ကို မှတ်မိကာ order အဟောင်းကိုပဲ ပြန်ပေးပါတယ်။

Core concept: resource, method, status

REST API တစ်ခုမှာ URL က noun (resource) ဖြစ်ပြီး method က verb ဖြစ်ပါတယ်။ Collection URL (/users) နဲ့ item URL (/users/7) ဆိုပြီး နှစ်မျိုး ရှိပါတယ်။ /getUser?id=7 ဒါမှမဟုတ် /deleteUser/7 လို URL ထဲမှာ verb ထည့်ရေးတာက REST ပုံစံ မဟုတ်ပါဘူး။ Method နဲ့ URL ပေါင်းစပ်မှုက လုပ်ငန်းကို ဖော်ပြပြီး status code က ရလဒ်ကို ပြောပါတယ်။

Requestလုပ်ငန်းအောင်မြင်ရင် status
GET /usersList ဖတ်200 + array
GET /users/7တစ်ခု ဖတ်200 (မရှိရင် 404)
POST /usersအသစ် ဖန်တီး201 + Location header
PUT /users/7အားလုံး အစားထိုး200 ဒါမှမဟုတ် 204
PATCH /users/7တစ်စိတ်တစ်ပိုင်း ပြင်200
DELETE /users/7ဖျက်204 No Content

Request တိုင်းက stateless ဖြစ်ပါတယ်: server က ယခင် request ကို မမှတ်ထားလို့ authentication token နဲ့ လိုအပ်တဲ့ context အားလုံးကို request တိုင်းမှာ ပို့ရပါတယ်။ Method တစ်ခုက idempotent ဖြစ်တယ်ဆိုတာ တစ်ကြိမ် ပို့တာနဲ့ အကြိမ်ကြိမ် ပို့တာ server ပေါ်မှာ ရလဒ် တူတယ်လို့ ဆိုလိုပါတယ်။ GET, PUT, DELETE က idempotent ဖြစ်ပြီး POST က မဟုတ်ပါဘူး၊ PATCH ကတော့ ဘယ်လို ရေးထားလဲ အပေါ် မူတည်ပါတယ်။

Collection ကြီးတွေကို တစ်ခါတည်း မပို့ပါဘူး။ Pagination, filter, sort တွေကို /orders?page=2&limit=20&status=paid&sort=-createdAt လို query parameter တွေနဲ့ ဖော်ပြပြီး response ထဲမှာ totalPages ဒါမှမဟုတ် next link လို စာမျက်နှာ အချက်အလက် ပါပါတယ်။ Error တွေအတွက်လည်း { error: "..." } လို တသမတ်တည်း ဖြစ်တဲ့ shape ကို သုံးတာက client code ကို ရိုးရှင်းစေပါတယ်။

PUT နဲ့ PATCH ကွာခြားချက်ကို သတိထားပါ။ PUT က 'ဒီ resource ကို ဒီ object အပြည့်အစုံနဲ့ အစားထိုး' လို့ ပြောတာဖြစ်လို့ ပို့မထားတဲ့ field တွေ ပျောက်သွားနိုင်ပါတယ်။ PATCH ကတော့ 'ဒီ field တွေကိုပဲ ပြောင်း' လို့ ပြောပါတယ်။ ဒါကြောင့် form တစ်ခုက field တစ်ခု နှစ်ခုကိုပဲ ပြင်တဲ့အခါ PATCH က ပိုသဘာဝကျပါတယ်။ ဘယ် method ကို API က လက်ခံလဲဆိုတာ documentation မှာ အမြဲ စစ်ပါ။

URL က noun၊ method က verb
  1. Resource ရွေး: /users ဒါမှမဟုတ် /users/7
  2. Verb ရွေး: GET POST PATCH PUT DELETE
  3. Data ကို JSON body/query နဲ့ ပို့
  4. Status က ရလဒ်ကို ပြော
  5. Retry မလုပ်ခင် idempotent လား မေး

URL ထဲမှာ verb (getUser, deleteOrder) ပါနေရင် REST ပုံစံ မဟုတ်ဘဲ RPC ပုံစံ ဖြစ်နေတတ်ပါတယ်။

အထွေထွေ ပုံစံ

javascript
async function request(method, path, data) {
  const response = await fetch(baseUrl + path, {
    method,                                  // GET, POST, PUT, PATCH, DELETE
    headers: { "Content-Type": "application/json", Authorization: auth },
    body: data ? JSON.stringify(data) : undefined,
  });
  if (!response.ok) throw new Error(`${method} ${path}: ${response.status}`);
  return response.status === 204 ? null : response.json();
}

Client တစ်ခုလုံးမှာ request function တစ်ခုပဲ ထားပြီး method, path, data ကိုပဲ ပြောင်းပါ။ 204 No Content မှာ body မပါလို့ json() ကို မခေါ်ပါနဲ့။

Worked example: in-memory REST server နဲ့ CRUD

User data တွေကို fetch(url, options) နဲ့ signature တူတဲ့ fakeServer ထဲမှာ ထားထားပါတယ်။ ဒါကြောင့် client က တကယ့် REST API ကို ခေါ်သလို method, URL, JSON body နဲ့ request ပို့ပြီး တကယ့် Response object တွေ ပြန်ရပါတယ်။ Request ခြောက်ခုက CRUD လုပ်ငန်း အားလုံးကို ဖုံးလွှမ်းပြီး နောက်ဆုံးတစ်ခုက ဖျက်ပြီးသား user အတွက် 404 ကို ပြပါတယ်။

rest-crud.js
// A tiny in-memory REST server with the same signature as fetch(url, options).
const users = [
  { id: 1, name: "Aung Kyaw", email: "aung@example.com" },
  { id: 2, name: "Su Su", email: "susu@example.com" },
];
let nextId = 3;

async function fakeServer(url, { method = "GET", body } = {}) {
  const { pathname } = new URL(url);
  const match = pathname.match(/^\/users(?:\/(\d+))?$/);
  if (!match) return Response.json({ error: "Not found" }, { status: 404 });
  const id = match[1] && Number(match[1]);
  const index = users.findIndex((u) => u.id === id);

  if (method === "GET" && !id) return Response.json(users);
  if (method === "GET" && index >= 0) return Response.json(users[index]);
  if (method === "POST" && !id) {
    const user = { id: nextId++, ...JSON.parse(body) };
    users.push(user);
    const headers = { Location: `/users/${user.id}` };
    return Response.json(user, { status: 201, headers });
  }
  if (method === "PATCH" && index >= 0) {
    Object.assign(users[index], JSON.parse(body));
    return Response.json(users[index]);
  }
  if (method === "DELETE" && index >= 0) {
    users.splice(index, 1);
    return new Response(null, { status: 204 });
  }
  return Response.json({ error: "User not found" }, { status: 404 });
}

// The client: one function that every REST call goes through.
async function request(method, path, data) {
  const response = await fakeServer(`https://api.example.com${path}`, {
    method,
    headers: data ? { "Content-Type": "application/json" } : {},
    body: data ? JSON.stringify(data) : undefined,
  });
  const body = response.status === 204 ? null : await response.json();
  console.log(`${method} ${path} -> ${response.status}`, body ?? "(no body)");
  return body;
}

async function main() {
  await request("GET", "/users");
  await request("GET", "/users/1");
  await request("POST", "/users", { name: "Min Min", email: "min@example.com" });
  await request("PATCH", "/users/3", { name: "Min Min Oo" });
  await request("DELETE", "/users/2");
  await request("GET", "/users/2");
}

main();

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

  1. Route by URLconst match = pathname.match(/^\/users(?:\/(\d+))?$/);

    Regex က /users (collection) နဲ့ /users/3 (item) နှစ်မျိုးလုံးကို ဖမ်းပြီး id ကို match[1] ထဲ ထည့်ပါတယ်။ တကယ့် server framework တွေက ဒါကို /users/:id လို route နဲ့ လုပ်ပေးပါတယ်။

  2. 201 plus Locationreturn Response.json(user, { status: 201, headers });

    POST အောင်မြင်ရင် 201 Created နဲ့ resource အသစ်ကို ပြန်ပေးပြီး Location header က URL အသစ် (/users/3) ကို ပြောပါတယ်။

  3. 204 has no bodyreturn new Response(null, { status: 204 });

    DELETE အောင်မြင်ရင် ပြန်ပို့စရာ data မရှိလို့ 204 No Content ကို body မပါဘဲ ပြန်ပေးပါတယ်။

  4. One request functionconst body = response.status === 204 ? null : await response.json();

    Client က 204 ကို သီးခြား ကိုင်တွယ်ပါတယ်၊ body အလွတ်ပေါ်မှာ json() ခေါ်ရင် SyntaxError ရလို့ပါ။

  5. Partial updateawait request("PATCH", "/users/3", { name: "Min Min Oo" });

    PATCH က ပို့တဲ့ field (name) ကိုပဲ ပြောင်းပြီး email ကို မထိပါဘူး။ PUT ဆိုရင် object တစ်ခုလုံးကို အစားထိုးလို့ email ကိုပါ ပို့ရပါမယ်။

You should see
GET /users -> 200 [
  { id: 1, name: 'Aung Kyaw', email: 'aung@example.com' },
  { id: 2, name: 'Su Su', email: 'susu@example.com' }
]
GET /users/1 -> 200 { id: 1, name: 'Aung Kyaw', email: 'aung@example.com' }
POST /users -> 201 { id: 3, name: 'Min Min', email: 'min@example.com' }
PATCH /users/3 -> 200 { id: 3, name: 'Min Min Oo', email: 'min@example.com' }
DELETE /users/2 -> 204 (no body)
GET /users/2 -> 404 { error: 'User not found' }
Retry မလုပ်ခင် ဆုံးဖြတ်ချက်
  1. Request fail ဖြစ်တယ်
  2. Network error, 5xx ဒါမှမဟုတ် 429 လား?
  3. Method က idempotent လား၊ ဒါမှမဟုတ် Idempotency-Key ပါလား?

နှစ်ခုလုံး ဟုတ်

Retry with backoff, same key

တစ်ခုခု မဟုတ်

Do not retry; show the error

Pagination: page နံပါတ်နဲ့ cursor

List endpoint တွေက pagination ပုံစံ နှစ်မျိုး သုံးလေ့ရှိပါတယ်။ Page နံပါတ် (offset) ပုံစံက နားလည်ရလွယ်ပြီး 'page 5 ကို တန်းသွား' လို့ ရပါတယ်။ ဒါပေမဲ့ ဖတ်နေရင်း item အသစ်တွေ ဝင်လာရင် item တွေ ထပ်နေတာ ဒါမှမဟုတ် ကျော်သွားတာ ဖြစ်နိုင်ပါတယ်။ Cursor ပုံစံကတော့ 'ဒီ item ရဲ့ နောက်ကနေ' လို့ မှတ်ထားလို့ data ပြောင်းနေတဲ့ feed တွေအတွက် ပိုတည်ငြိမ်ပါတယ်။

ပုံစံRequest ဥပမာသင့်တော်တဲ့နေရာ
Page / offsetGET /orders?page=3&limit=20Admin table၊ page နံပါတ် ပြချင်ရင်
CursorGET /orders?after=ord_81&limit=20Infinite scroll၊ အမြဲ ပြောင်းနေတဲ့ feed

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

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

Public API အများစု (GitHub, Stripe, Shopify စသဖြင့်) နဲ့ ကိုယ်ပိုင် backend အများစုက REST ပုံစံကို လိုက်နာပါတယ်။ Frontend team တွေက resource တစ်ခုစီအတွက် client module တစ်ခု (usersApi.list, usersApi.get, usersApi.update) ရေးပြီး component တွေက URL နဲ့ status code ကို တိုက်ရိုက် မထိတွေ့ရပါဘူး။

  • Payment provider တချို့ (ဥပမာ Stripe) က POST request တွေအတွက် Idempotency-Key header ကို ထောက်ပံ့ပါတယ်၊ checkout code က attempt တိုင်းမှာ key တူတူကို ပို့ပါတယ်။
  • Admin table တွေက ?page=&limit= ဒါမှမဟုတ် cursor ပုံစံ pagination နဲ့ data ကို တစ်ပိုင်းချင်း load လုပ်ပြီး filter ပြောင်းတိုင်း page 1 ကနေ ပြန်စပါတယ်။
  • User နှစ်ယောက် တစ်ချိန်တည်း ပြင်တဲ့အခါ server က 409 Conflict ဒါမှမဟုတ် 412 Precondition Failed ကို ပြန်ပေးပြီး client က နောက်ဆုံး version ကို ပြန်ဖတ်ခိုင်းပါတယ်။

အမှားများ

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

POST ကို မျက်စိမှိတ် retry လုပ်ခြင်း

Network error ရတိုင်း POST ကို ထပ်ပို့ရင် order, payment, message တွေ ထပ်နေနိုင်ပါတယ်။ Server က idempotency key ကို ထောက်ပံ့မှသာ retry လုပ်ပါ၊ မထောက်ပံ့ရင် user ကို 'order ဖြစ်မဖြစ် စစ်ကြည့်ပါ' လို့ ပြပါ။

PATCH နေရာမှာ PUT သုံးခြင်း

PUT က resource တစ်ခုလုံးကို အစားထိုးပါတယ်။ { name } ကိုပဲ PUT နဲ့ ပို့ရင် API က email လို တခြား field တွေကို ဖျက်ပစ်နိုင်ပါတယ်။ Field အနည်းငယ်ကိုပဲ ပြောင်းချင်ရင် PATCH ကို သုံးပါ။

204 response ပေါ်မှာ json() ခေါ်ခြင်း

DELETE က 204 No Content ကို body မပါဘဲ ပြန်ပေးလေ့ရှိပါတယ်။ response.json() ကို ခေါ်ရင် 'Unexpected end of JSON input' လို SyntaxError ရပြီး အောင်မြင်တဲ့ delete ကို error အဖြစ် ပြမိပါတယ်။

Best Practices

Best practices

  • Resource တစ်ခုစီအတွက် client function တွေကို module တစ်ခုထဲ စုထားပြီး component တွေက URL ကို မသိပါစေနဲ့။
  • Retry ကို network error, 5xx နဲ့ 429 အတွက်ပဲ ကန့်သတ်ပြီး POST တွေမှာ idempotency key မပါရင် retry မလုပ်ပါနဲ့။
  • List တွေကို အမြဲ page လိုက် ဖတ်ပါ၊ 'အားလုံးကို တစ်ခါတည်း' ဆိုတဲ့ endpoint ကို အားမကိုးပါနဲ့။

Mini challenge

Mini challenge: idempotent createOrder နဲ့ pagination

ပေးထားတဲ့ shopServer က dropNextResponse ကို true ထားရင် order ကို သိမ်းပြီး response ကို 'ပျောက်' စေပါတယ်။ Network error ကိုပဲ retry လုပ်တဲ့ createOrder နဲ့ စာမျက်နှာ အားလုံး ဖတ်တဲ့ listAllOrders ကို ရေးပါ။ Idempotency key ပါရင် order တစ်ခုပဲ ဖြစ်ပြီး key မပါရင် duplicate ဖြစ်တာကို ပြပါ။

  • createOrder က crypto.randomUUID() နဲ့ key ကို retry မစခင် တစ်ကြိမ်ပဲ ဖန်တီးရမယ်
  • TypeError (network error) ကိုပဲ retry လုပ်ပြီး HTTP error ကို ချက်ချင်း throw လုပ်ရမယ်
  • listAllOrders က page=1 ကနေ စပြီး totalPages အထိ limit=2 နဲ့ ဖတ်ရမယ်
  • နောက်ဆုံးမှာ order အားလုံးကို id:item ပုံစံနဲ့ print ထုတ်ပါ
orders-client.js
// Fake order service. When dropNextResponse is true, the server SAVES the
// order but the response is lost, like a connection dropping mid-request.
const orders = [
  { id: 1, item: "Tea" },
  { id: 2, item: "Coffee" },
  { id: 3, item: "Cake" },
];
const savedByKey = new Map();
let dropNextResponse = false;

async function shopServer(url, { method = "GET", headers, body } = {}) {
  const { pathname, searchParams } = new URL(url);
  if (method === "GET" && pathname === "/orders") {
    const page = Number(searchParams.get("page") ?? 1);
    const limit = Number(searchParams.get("limit") ?? 2);
    const items = orders.slice((page - 1) * limit, page * limit);
    return Response.json({ items, page, totalPages: Math.ceil(orders.length / limit) });
  }
  if (method === "POST" && pathname === "/orders") {
    const key = new Headers(headers).get("idempotency-key");
    const earlier = key && savedByKey.get(key);
    if (earlier) return Response.json(earlier, { status: 201 });
    const order = { id: orders.length + 1, ...JSON.parse(body) };
    orders.push(order);
    if (key) savedByKey.set(key, order);
    if (dropNextResponse) {
      dropNextResponse = false;
      throw new TypeError("connection reset");
    }
    return Response.json(order, { status: 201 });
  }
  return Response.json({ error: "Not found" }, { status: 404 });
}

const BASE = "https://shop.example.com";

async function createOrder(data, fetchFn, { idempotent = true, attempts = 3 } = {}) {
  // TODO: build headers; add an Idempotency-Key once when idempotent is true
  // TODO: loop: POST, throw on !response.ok, return the JSON on success
  // TODO: catch: retry only a TypeError and only while attempts remain
}

async function listAllOrders(fetchFn) {
  // TODO: GET /orders?page=N&limit=2 until page > totalPages, collect items
}

// TODO: main(): set dropNextResponse = true, create "Juice" with a key;
// set it again, create "Soup" with { idempotent: false }; print all orders

ရလဒ်: Key ပါတဲ့ Juice အတွက် attempt 1 fail ဖြစ်ပြီး retry လုပ်ကာ order 4 တစ်ခုပဲ ရပါတယ်။ Key မပါတဲ့ Soup ကတော့ order 5 နဲ့ 6 နှစ်ခု ဖြစ်သွားလို့ နောက်ဆုံး line က 1:Tea, 2:Coffee, 3:Cake, 4:Juice, 5:Soup, 6:Soup ဖြစ်ပါတယ်။

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

Key ကို loop အပြင်မှာ ဖန်တီးပါ၊ loop ထဲမှာ ဖန်တီးရင် retry တိုင်း key အသစ်ဖြစ်ပြီး server က မှတ်မိမှာ မဟုတ်ပါဘူး။ do...while က page တစ်ခုကို အနည်းဆုံး တစ်ကြိမ် ဖတ်ဖို့ အဆင်ပြေပါတယ်။

အဖြေ ကြည့်ရန်
orders-client.js
// Fake order service. When dropNextResponse is true, the server SAVES the
// order but the response is lost, like a connection dropping mid-request.
const orders = [
  { id: 1, item: "Tea" },
  { id: 2, item: "Coffee" },
  { id: 3, item: "Cake" },
];
const savedByKey = new Map();
let dropNextResponse = false;

async function shopServer(url, { method = "GET", headers, body } = {}) {
  const { pathname, searchParams } = new URL(url);
  if (method === "GET" && pathname === "/orders") {
    const page = Number(searchParams.get("page") ?? 1);
    const limit = Number(searchParams.get("limit") ?? 2);
    const items = orders.slice((page - 1) * limit, page * limit);
    return Response.json({ items, page, totalPages: Math.ceil(orders.length / limit) });
  }
  if (method === "POST" && pathname === "/orders") {
    const key = new Headers(headers).get("idempotency-key");
    const earlier = key && savedByKey.get(key);
    if (earlier) return Response.json(earlier, { status: 201 });
    const order = { id: orders.length + 1, ...JSON.parse(body) };
    orders.push(order);
    if (key) savedByKey.set(key, order);
    if (dropNextResponse) {
      dropNextResponse = false;
      throw new TypeError("connection reset");
    }
    return Response.json(order, { status: 201 });
  }
  return Response.json({ error: "Not found" }, { status: 404 });
}

const BASE = "https://shop.example.com";

async function createOrder(data, fetchFn, { idempotent = true, attempts = 3 } = {}) {
  const headers = { "Content-Type": "application/json" };
  if (idempotent) headers["Idempotency-Key"] = crypto.randomUUID(); // reused on retry
  for (let attempt = 1; ; attempt++) {
    try {
      const response = await fetchFn(`${BASE}/orders`, {
        method: "POST",
        headers,
        body: JSON.stringify(data),
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}`); // not retried
      return await response.json();
    } catch (error) {
      const retryable = error instanceof TypeError; // network failures only
      if (!retryable || attempt === attempts) throw error;
      console.log(`  attempt ${attempt} failed (${error.message}), retrying`);
    }
  }
}

async function listAllOrders(fetchFn) {
  const all = [];
  let page = 1;
  let totalPages = 1;
  do {
    const response = await fetchFn(`${BASE}/orders?page=${page}&limit=2`);
    const body = await response.json();
    all.push(...body.items);
    totalPages = body.totalPages;
    page += 1;
  } while (page <= totalPages);
  return all;
}

async function main() {
  console.log("with an idempotency key:");
  dropNextResponse = true;
  const juice = await createOrder({ item: "Juice" }, shopServer);
  console.log("  created", juice);

  console.log("without a key:");
  dropNextResponse = true;
  await createOrder({ item: "Soup" }, shopServer, { idempotent: false });

  const all = await listAllOrders(shopServer);
  console.log("all orders:", all.map((o) => `${o.id}:${o.item}`).join(", "));
}

main();

Quick Quiz 1 / 3

User နံပါတ် 7 ရဲ့ email တစ်ခုတည်းကို ပြောင်းချင်တယ်။ REST ပုံစံနဲ့ အကိုက်ညီဆုံး request က ဘယ်ဟာလဲ?

Quick Quiz 2 / 3

ဘယ် request ကို network error ပြီးနောက် ထပ်ပို့ရင် server ပေါ်မှာ မလိုလားအပ်တဲ့ ရလဒ် ဖြစ်နိုင်ဆုံးလဲ?

Quick Quiz 3 / 3

DELETE /users/2 က 204 ကို ပြန်ပေးတယ်။ client က await response.json() ကို ခေါ်ရင် ဘာဖြစ်မလဲ?

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

  • REST မှာ URL က resource (noun) ဖြစ်ပြီး HTTP method က လုပ်ငန်း (verb) ဖြစ်ပါတယ်။
  • POST → 201 + Location၊ GET → 200၊ DELETE → 204၊ မရှိတဲ့ resource → 404 ဆိုတာ ပုံမှန် pattern ပါ။
  • GET, PUT, DELETE က idempotent ဖြစ်ပြီး POST က မဟုတ်လို့ retry လုပ်ဖို့ idempotency key လိုပါတယ်။
  • Pagination, filter, sort ကို query parameter နဲ့ ဖော်ပြပြီး စာမျက်နှာ အားလုံးကို totalPages အထိ ဖတ်ပါ။

MDN — Fetch API — MDN Web Docs

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

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

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

REST API Integration | Thuta Learning