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

Update User

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

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

  • PUT နဲ့ PATCH ကို ရွေးပြီး optional field တစ်ခု မပါတဲ့အခါ ဘာကွာလဲ ပြနိုင်ဖို့
  • PATCH မှာ မပါတဲ့ field (missing) နဲ့ ထင်ရှားတဲ့ null ကို မတူအောင် ကိုင်တွယ်နိုင်ဖို့
  • Server ပိုင် field (id, role) တွေကို မပြောင်းနိုင်အောင် ထိန်းပြီး merge လုပ်ပြီးသား ရလဒ်ကို validate လုပ်နိုင်ဖို့
  • ETag နဲ့ If-Match သုံးပြီး lost update ကို ကာကွယ်ကာ 412 ကို ပြန်ဖတ်ပြီး ထပ်ကြိုးစားတာနဲ့ ဖြေရှင်းနိုင်ဖို့

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

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

Update ဆိုတာ ရှိပြီးသား ဖိုင်ကို ပြင်တာပါ။ ပြင်ချက်ကို ပေးတဲ့နည်း နှစ်နည်းရှိပါတယ်။ PUT က ပုံစံတစ်ခုလုံးကို ပြန်ပေးတာနဲ့ တူပါတယ်: "user က အခု ဒီလိုပုံစံပါ" လို့ ပြောတာဖြစ်ပြီး မထည့်ခဲ့တဲ့ field တွေ ပျောက်သွားပါတယ်။ PATCH ကတော့ sticky note တစ်ခုပါ: "name ကို Alice K. လို့ ပြောင်းပါ"၊ ကျန်တာအားလုံး မပြောင်းပါဘူး။ ဒုတိယပြဿနာက လူနှစ်ယောက် တစ်ပြိုင်နက် ပြင်တာပါ။ သင်နဲ့ လုပ်ဖော်ကိုင်ဖက်က Bob ရဲ့ ဖိုင်ကို နှစ်ယောက်လုံး ဖွင့်ပြီး နှစ်ယောက်လုံး သိမ်းရင် နောက်ဆုံးသိမ်းတဲ့သူက ကျန်သူရဲ့ ပြင်ချက်ကို တိတ်တိတ်ဖျက်ပစ်ပါလိမ့်မယ်၊ server က ဖိုင်ဟာ သင်စတင်ခဲ့တဲ့ version အတိုင်းပဲလို့ မစစ်ဘူးဆိုရင်ပါ။

Problem → Why → Solution

ပြဿနာ: နောက်ဆုံးရေးတာက နိုင်တယ် (last write wins)

Support ဝန်ထမ်းတစ်ယောက်က Alice ရဲ့ profile ကို ဖွင့်ပြီး name ပြောင်းပါတယ်။ အဲဒီအချိန်တည်းမှာ admin တစ်ယောက်က သူ့ bio ကို ပြင်ပါတယ်။ Screen နှစ်ခုလုံး record တူကို load လုပ်ထားတာပါ။ ဝန်ထမ်းရဲ့ tool က PUT နဲ့ သိမ်းပြီး အဟောင်း bio ပါတဲ့ ပုံစံတစ်ခုလုံးကို ပြန်ပို့လို့ admin ရဲ့ ပြင်ချက် ပျောက်သွားပြီး ဘယ်သူမှ error မမြင်ရပါဘူး။ ဒါက lost update ပါ။ Endpoint တူထဲမှာ bug ဒုတိယတစ်ခုလည်း ပုန်းနေပါတယ်: { "name": "Alice K." } တစ်ခုတည်းနဲ့ PUT /v1/users/u_1 လုပ်ရင် client မပြောခဲ့တဲ့ field အားလုံး reset ဖြစ်သွားပြီး "role": "admin" ပါတဲ့ request က member ကို ကိုယ့်ကိုယ်ကိုယ် ရာထူးတိုးခွင့် ပေးပါတယ်။

last-write-wins.js
// Last write wins: no version check, and the body overwrites everything
app.put("/v1/users/:id", async (req, res) => {
  await db.users.update(req.params.id, req.body); // role, id... all writable
  res.json(await db.users.findById(req.params.id));
});

နှစ်ခုစလုံး တိတ်တိတ်ပဲ မှားတယ်

ပြဿနာနှစ်ခု တိတ်တိတ်ကလေး ဖြစ်ပါတယ်။ Server က "ကျွန်တော့်မှာ အခုရှိတဲ့ version ကို ပြင်နေတာလား" လို့ မမေးလို့ ဟောင်းနေတဲ့ client က ပိုသစ်တဲ့ data ကို ထပ်ရေးနိုင်ပါတယ်၊ ပြီးတော့ အလျင်စလို merge လုပ်တာက caller မထိချင်တဲ့ field တွေကို reset ဒါမှမဟုတ် overwrite လုပ်နိုင်ပါတယ်။ နှစ်ခုလုံးက error message မထုတ်လို့ user တစ်ယောက်က တိုင်မှသာ သိရတာပါ။

Core concept: PUT, PATCH နဲ့ version စစ်ဆေးမှု

PUT က ပို့လိုက်တဲ့ body နဲ့ resource ရဲ့ writable representation ကို အစားထိုးပါတယ်။ Idempotent ဖြစ်ပါတယ်: နှစ်ကြိမ်ပို့လည်း ရလဒ်တူပါတယ်။ ချန်ထားတဲ့ field တွေက default ပြန်ဖြစ်ပါတယ် (ဒီမှာ bio က null ဖြစ်တယ်)၊ လိုအပ်တဲ့ field တွေ ပါရမှာမို့ name တစ်ခုတည်းနဲ့ PUT /v1/users/u_1 လုပ်ရင် 422 ပါ။ PATCH က body ထဲ ပါတဲ့ field တွေကိုပဲ ပြောင်းပြီး ကျန်တာ မထိပါဘူး။ PATCH ကို HTTP စံက idempotent ဖြစ်မယ်လို့ အာမမခံပါဘူး ("တစ်ခု တိုး" လို patch က idempotent မဟုတ်ပါ)၊ field တွေကို တန်ဖိုးသတ်မှတ်တဲ့ patch ကတော့ ဖြစ်ပါတယ်။ API အများစုက form ပြင်တာကို PATCH နဲ့၊ "document တစ်ခုလုံး သိမ်းမယ်" ကို PUT နဲ့ သုံးကြပါတယ်။

PATCH မှာ မပါတဲ့ field ဆိုတာ "မထိနဲ့" လို့ ဆိုလိုပြီး ထင်ရှားတဲ့ null ဆိုတာ "ဖျက်ပါ" လို့ ဆိုလိုပါတယ်။ { "name": "Alice K." } က bio ကို မပြောင်းပါဘူး၊ { "bio": null } က bio ကို ဖျက်ပါတယ်။ JavaScript မှာ 'bio' in body နဲ့ ခွဲလို့ရတာမို့ server က truthiness မဟုတ်ဘဲ key ရှိမရှိကို စစ်ပါတယ်။ Truthiness နဲ့ စစ်ရင် တန်ဖိုးတစ်ခုကို ဖျက်တာ ဒါမှမဟုတ် စာလုံးအလွတ်ကို သတ်မှတ်တာ မလုပ်နိုင်တော့ပါဘူး။ လိုအပ်တဲ့ field တွေကိုတော့ ဖျက်လို့ မရပါဘူး: { "email": null } က 422 ပါ။

MethodBody ရဲ့ အဓိပ္ပာယ်မထည့်ခဲ့တဲ့ field
PUTWritable representation တစ်ခုလုံးReset ဖြစ် (bio က null)၊ လိုအပ်တာဆို 422
PATCHပြောင်းမယ့် field တွေပဲမထိဘဲ ထားခဲ့
PATCH { bio: null }ဒီ field တစ်ခုကို ဖျက်key ပါနေလို့ မသက်ဆိုင်

Method နှစ်ခုလုံးက ဖန်တီးတဲ့အခါ စည်းမျဉ်းတွေ တူတူသုံးပါတယ်: name, email, bio ပဲ ရေးလို့ရပြီး id နဲ့ role က body ထဲပါလည်း လျစ်လျူရှုခံရပါတယ်၊ merge လုပ်ပြီးတဲ့ ရလဒ်တစ်ခုလုံးကို validate လုပ်ပါတယ်၊ ဘာလို့လဲဆိုတော့ တစ်ခုတည်းဆို အဆင်ပြေတဲ့ PATCH က record မမှန်တာ ဖြစ်စေနိုင်လို့ပါ။ Email ကို တခြား user ပိုင်တဲ့ email သို့ ပြောင်းရင် create မှာလိုပဲ 409 ပါ။ မရှိတဲ့ user ကတော့ 404 ပါ၊ update က user ကို ဘယ်တော့မှ အသစ် မဖန်တီးပါဘူး။

Lost update ကို ကာကွယ်ဖို့ user version တစ်ခုစီကို ETag ပေးပြီး client က ဘယ် version ကို ပြင်နေလဲ ပြောခိုင်းပါ: If-Match: "v2"။ Server က လက်ရှိ ETag နဲ့ နှိုင်းယှဉ်ပါတယ်။ တူရင် write လုပ်ပြီး response မှာ ETag အသစ် ("v3") ပါပါတယ်။ ကြားထဲမှာ တခြား client သိမ်းသွားရင် ETag ပြောင်းသွားပြီဖြစ်လို့ server က ဘာမှ မပြောင်းဘဲ 412 Precondition Failed ပြန်ပါတယ်။ ရှုံးတဲ့သူက user ကို ပြန်ဖတ်ပြီး ဘယ်လို merge မလဲ ဆုံးဖြတ်ကာ (ဒါမှမဟုတ် လူကို မေးပြီး) ETag အသစ်နဲ့ ပြန်ပို့ပါတယ်။ ဒါကို optimistic concurrency လို့ခေါ်ပြီး ဘာကိုမှ lock မလုပ်ပါဘူး: conflict ရှားတယ်လို့ ယူဆပြီး ဖြစ်လာမှ ဖော်ထုတ်တာပါ။ If-Match ကို optional (ဒီ sample မှာလို header မပါရင် last-write-wins) ထားမလား၊ မဖြစ်မနေ (428 Precondition Required ပြန်) ထားမလားက policy ရွေးချယ်မှုပါ၊ လူက ကိုယ်တိုင်ပြင်တဲ့ data အတွက် မဖြစ်မနေ ထားတာ ပိုလုံခြုံပါတယ်။

Version စစ်၊ merge၊ validate၊ bump
  1. Client က user နဲ့ ETag ကို ဖတ်
  2. PUT/PATCH + If-Match ကို ပို့
  3. Server က merge လုပ်ပြီး ရလဒ်ကို validate
  4. ETag တူလား? သိမ်းပြီး တိုး၊ မဟုတ်ရင် 412

If-Match က ကတိတစ်ခုပါ: "ဒီ ပြင်ချက်ကို user က ကျွန်တော်မြင်ခဲ့တဲ့ version အတိုင်းပဲ ရှိနေမှသာ လုပ်ပါ"။

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

text
PATCH /v1/<collection>/<id>
If-Match: "<etag from the last read>"
Content-Type: application/json

{ <only the fields to change; null clears one> }

200 OK  ETag: "<new etag>"  { <the updated resource> }
412 Precondition Failed      (someone else changed it first)

နောက်ဆုံး ဖတ်ခဲ့တဲ့ ETag ကို If-Match အဖြစ် ပြန်ပို့ပါတယ်။ အောင်မြင်ရင် ETag အသစ်နဲ့ resource အသစ်ကို ရပြီး တခြားသူ အရင်ပြောင်းသွားရင် 412 ရပါတယ်။

Worked example: PUT, PATCH နဲ့ stale update

ဒီ sample က random local port တစ်ခုမှာ users API ကို run ပါတယ်၊ Alice နဲ့ Bob ပါပါတယ်။ ပထမ ခြောက်ကြောင်းက PUT/PATCH ကွာခြားချက်ကို ပြပါတယ်: PATCH က bio ကို ထိမ်းထားတာ၊ PUT က bio ကို null လုပ်တာ၊ email မပါတဲ့ PUT က 422၊ id နဲ့ role ကို လျစ်လျူရှုတာ၊ null နဲ့ bio ဖျက်တာ၊ တခြားသူ email သို့ ပြောင်းတာက 409။ နောက်ဆုံး သုံးကြောင်းက client နှစ်ခု Bob ကို တစ်ပြိုင်နက် ဖတ်တဲ့ အခြေအနေပါ: A က သိမ်းနိုင်တယ်၊ B က 412 ရတယ်၊ B က ပြန်ဖတ်ပြီး ထပ်လုပ်လို့ ရတယ်။

users-update.mjs
import http from "node:http";

// The users API (stands in for https://api.example.com/v1/users)
const row = (n, name, role, bio = null) => ({
  id: "u_" + n,
  name,
  email: name.toLowerCase() + "@example.com",
  role,
  bio,
  version: 1,
});
const users = new Map([
  ["u_1", row(1, "Alice", "admin", "Maintainer")],
  ["u_2", row(2, "Bob", "member")],
]);

const WRITABLE = ["name", "email", "bio"]; // id and role are never taken from a body
const publicView = ({ id, name, email, role, bio }) => ({ id, name, email, role, bio });
const etagOf = (user) => '"v' + user.version + '"';
const looksLikeEmail = (s) => typeof s === "string" && /^[^@ ]+@[^@ ]+[.][^@ ]+$/.test(s);

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

async function readJsonObject(req) {
  let raw = "";
  for await (const chunk of req) raw += chunk;
  try {
    const value = JSON.parse(raw);
    return value?.constructor === Object ? value : null; // plain objects only
  } catch {
    return null;
  }
}

// PUT replaces the writable representation; PATCH changes only what was sent
function merge(method, user, input) {
  const next = { ...user };
  for (const key of WRITABLE) {
    if (key in input) next[key] = input[key]; // sent: take it (null clears)
    else if (method === "PUT") next[key] = null; // PUT: a missing field is reset
  }
  return next;
}

function validate(user) {
  const fields = {};
  if (typeof user.name !== "string" || !user.name.trim()) fields.name = "is required";
  if (user.email === null) fields.email = "is required";
  else if (!looksLikeEmail(user.email)) fields.email = "must be a valid email address";
  return fields;
}

const server = http.createServer(async (req, res) => {
  const [, , resource, id] = new URL(req.url, "http://localhost").pathname.split("/");
  const user = users.get(id);
  if (resource !== "users" || !user) {
    return fail(res, 404, "user_not_found", "No user " + id);
  }
  if (req.method === "GET") {
    return send(res, 200, publicView(user), { ETag: etagOf(user) });
  }
  if (req.method !== "PUT" && req.method !== "PATCH") {
    const error = { code: "method_not_allowed", message: "Use GET, PUT or PATCH" };
    return send(res, 405, { error }, { Allow: "GET, PUT, PATCH" });
  }

  // Optimistic concurrency: a client that names the version it edited
  // must still be looking at the current one
  const ifMatch = req.headers["if-match"];
  if (ifMatch && ifMatch !== etagOf(user)) {
    return fail(res, 412, "precondition_failed", "The user changed since you read it");
  }

  const input = await readJsonObject(req);
  if (!input) return fail(res, 400, "invalid_json", "Body must be a JSON object");

  const next = merge(req.method, user, input);
  const fields = validate(next);
  if (Object.keys(fields).length) {
    return fail(res, 422, "validation_failed", "One or more fields are invalid", fields);
  }
  next.email = next.email.trim().toLowerCase();
  const taken = [...users.values()].some((u) => u.id !== id && u.email === next.email);
  if (taken) {
    return fail(res, 409, "email_taken", "A user with this email already exists");
  }

  next.version = user.version + 1;
  users.set(id, next);
  send(res, 200, publicView(next), { ETag: etagOf(next) });
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = "http://127.0.0.1:" + server.address().port;

// The client
async function call(method, path, body, headers = {}) {
  const res = await fetch(base + path, {
    method,
    headers: { "Content-Type": "application/json", ...headers },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  return { status: res.status, etag: res.headers.get("etag"), data: await res.json() };
}
function show(label, r) {
  const detail = r.data.error
    ? r.data.error.code + " " + JSON.stringify(r.data.error.fields ?? {})
    : JSON.stringify(r.data, ["name", "bio", "role"]);
  console.log(label.padEnd(14), r.status, r.etag ?? "-", detail);
}

const alice = "/v1/users/u_1";
const bob = "/v1/users/u_2";
show("PATCH name", await call("PATCH", alice, { name: "Alice K." }));
const keepEmail = { name: "Alice K.", email: "alice@example.com" };
show("PUT, no bio", await call("PUT", alice, keepEmail));
show("PUT, no email", await call("PUT", alice, { name: "Alice K." }));
show("PATCH extras", await call("PATCH", bob, { id: "u_9", role: "admin", bio: "Hi" }));
show("PATCH null", await call("PATCH", bob, { bio: null }));
show("PATCH email", await call("PATCH", bob, { email: "alice@example.com" }));

// Two clients read Bob at the same moment...
const a = await call("GET", bob);
const b = await call("GET", bob);
show("A saves", await call("PATCH", bob, { name: "Robert" }, { "If-Match": a.etag }));
show("B is stale", await call("PATCH", bob, { name: "Bobby" }, { "If-Match": b.etag }));
// ...B re-reads, sees Robert, and edits again on top of the fresh version
const fresh = await call("GET", bob);
const retry = { "If-Match": fresh.etag };
show("B retries", await call("PATCH", bob, { bio: "Hi from B" }, retry));
server.close();

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

  1. Writable allowlistconst WRITABLE = ["name", "email", "bio"]; // id and role are never taken from a body

    merge က ဒီစာရင်းထဲက key တွေကိုပဲ input ကနေ ကူးယူပါတယ်၊ ဒါကြောင့် PATCH extras line မှာ id: "u_9", role: "admin" ပို့ပေမဲ့ မပြောင်းပါဘူး။

  2. Present versus missingif (key in input) next[key] = input[key]; // sent: take it (null clears)

    key ရှိရင် တန်ဖိုးကို ယူပြီး null ဆိုရင်လည်း ယူတာမို့ PATCH { bio: null } က bio ကို ဖျက်ပါတယ်။ in operator က key ရှိမရှိကိုပဲ ကြည့်ပြီး တန်ဖိုး truthy ဟုတ်မဟုတ် မကြည့်ပါဘူး။

  3. PUT resetselse if (method === "PUT") next[key] = null; // PUT: a missing field is reset

    PUT မှာ ပို့မလာတဲ့ writable field တိုင်းကို null ပြောင်းလို့ bio မပါတဲ့ PUT က bio ကို ဖျက်ပြီး name သို့ email မပါရင် validate ကျပါတယ်။

  4. Validate the merged resultconst fields = validate(next);

    Input ကို တိုက်ရိုက်မစစ်ဘဲ merge ပြီးသား record ကို စစ်ပါတယ်၊ ဒါမှ PUT ရော PATCH ရော စည်းမျဉ်းတူတူ သုံးပြီး email: null လို ပြဿနာကို ဖမ်းနိုင်ပါတယ်။

  5. The preconditionif (ifMatch && ifMatch !== etagOf(user)) {

    Client ပို့တဲ့ If-Match က လက်ရှိ ETag နဲ့ မတူရင် ဘာမှ မရေးဘဲ 412 ပြန်ပါတယ်။ B ရဲ့ "v3" က A သိမ်းပြီးနောက် "v4" နဲ့ မတူတော့ပါဘူး။

  6. Bump the versionnext.version = user.version + 1;

    အောင်မြင်တဲ့ write တိုင်း version တက်ပြီး ETag အသစ်ထွက်ပါတယ်။ Validation ကျတာ၊ 409၊ 412 တွေမှာ version မတက်ပါဘူး၊ ဘာမှ မပြောင်းလို့ပါ။

You should see
PATCH name     200 "v2" {"name":"Alice K.","bio":"Maintainer","role":"admin"}
PUT, no bio    200 "v3" {"name":"Alice K.","bio":null,"role":"admin"}
PUT, no email  422 - validation_failed {"email":"is required"}
PATCH extras   200 "v2" {"name":"Bob","bio":"Hi","role":"member"}
PATCH null     200 "v3" {"name":"Bob","bio":null,"role":"member"}
PATCH email    409 - email_taken {}
A saves        200 "v4" {"name":"Robert","bio":null,"role":"member"}
B is stale     412 - precondition_failed {}
B retries      200 "v5" {"name":"Robert","bio":"Hi from B","role":"member"}
PUT/PATCH ကို server က ကိုင်တွယ်ပုံ
  1. User ရှိမရှိ ရှာ (မရှိရင် 404)
  2. If-Match ကို လက်ရှိ ETag နဲ့ နှိုင်းယှဉ်
  3. Allowlist field တွေကို merge လုပ်
  4. Validate၊ email ထပ်မထပ်စစ်၊ သိမ်းပြီး version တိုး

ETag တူပြီး validation အောင်

200 with the updated user and a new ETag

ETag မတူ ဒါမှမဟုတ် validation ကျ

412, 422 or 409 and nothing is written

412 ရတဲ့အခါ ဘာလုပ်မလဲ

412 က error သက်သက် မဟုတ်ဘဲ "တခြားသူ ပြောင်းသွားပြီ" ဆိုတဲ့ သတင်းပါ။ Client က အလိုအလျောက် ထပ်ပို့လို့ မရပါဘူး၊ ဘာလို့လဲဆိုတော့ အဟောင်း ETag နဲ့ ထပ်ပို့ရင် ထပ်ပြီး 412 ရမှာမို့ပါ၊ If-Match ကို ဖြုတ်ပြီး ပို့ရင်တော့ တခြားသူရဲ့ ပြင်ချက်ကို ဖျက်ပစ်မှာပါ။ မှန်တဲ့ အစီအစဉ်က ဒီလိုပါ။

User ကို ပြန်ဖတ်

GET /v1/users/u_2 နဲ့ လက်ရှိ version နဲ့ ETag အသစ်ကို ယူပါ။

ကွာခြားချက်ကို ဆုံးဖြတ်

ပြောင်းထားတဲ့ field က မတူရင် (A က name၊ B က bio) အလိုအလျောက် ပေါင်းလို့ရပါတယ်။ field တူပြောင်းထားရင် user ကို ပြပြီး ဘာကိုရွေးမလဲ မေးပါ။

ETag အသစ်နဲ့ ပြန်ပို့

If-Match: ETag အသစ် နဲ့ ပြင်ချက်ကို ပြန်ပို့ပါ။ ထပ်ပြီး 412 ရရင် ဒီအစီအစဉ်ကို ကြိုးစားမှု အကန့်အသတ်နဲ့ ထပ်လုပ်ပါ။

text
PATCH /v1/users/u_2 HTTP/1.1
Host: api.example.com
Content-Type: application/json
If-Match: "v3"

{ "name": "Bobby" }

HTTP/1.1 412 Precondition Failed
Content-Type: application/json

{ "error": { "code": "precondition_failed",
             "message": "The user changed since you read it" } }

curl နဲ့ PATCH ပို့ခြင်းနဲ့ JSON Merge Patch

ဒီသင်ခန်းစာရဲ့ PATCH ပုံစံ (ပြောင်းမယ့် field ပဲ ပို့၊ null က ဖျက်) ကို JSON Merge Patch (RFC 7396၊ media type က application/merge-patch+json) အဖြစ် စံသတ်မှတ်ထားပါတယ်။ ကန့်သတ်ချက်က array ကို တစ်ခုလုံး အစားထိုးတာနဲ့ null ကို တန်ဖိုးအဖြစ် သတ်မှတ်လို့ မရတာပါ။ ပိုရှုပ်ထွေးတဲ့ ပြင်ချက်တွေအတွက် JSON Patch (RFC 6902) က လုပ်ဆောင်ချက်စာရင်းတစ်ခု ပို့ပါတယ်။ API တချို့က application/json ကိုပဲ လက်ခံပြီး တချို့က merge-patch media type ကို မဖြစ်မနေ တောင်းပါတယ်၊ docs ကို စစ်ပါ။

bash
curl -i -X PATCH https://api.example.com/v1/users/u_2 \
  -H "Content-Type: application/json" \
  -H 'If-Match: "v3"' \
  -d '{"name":"Bobby"}'

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

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

လူတွေ ကိုယ်တိုင် ပြင်တဲ့ data (profile, ပစ္စည်းဖော်ပြချက်, document) တိုင်းမှာ lost update အန္တရာယ် ရှိပါတယ်၊ ဒါကြောင့် admin console တွေ၊ CMS တွေနဲ့ ပူးပေါင်းရေးတဲ့ app တွေက ETag သို့ version field ကို သုံးကြပါတယ်။ API တချို့က header အစား body ထဲက version သို့ updated_at field ကို သုံးပါတယ်၊ အယူအဆက အတူတူပါပဲ။ Mobile app က offline မှာ ပြင်ခဲ့တာကို ပြန် sync လုပ်တဲ့အခါလည်း version စစ်ပြီး conflict ကို ဖော်ထုတ်ပါတယ်။

  • Frontend form က PATCH ကို ပို့ပြီး ပြောင်းတဲ့ field ကိုပဲ ပါစေပါတယ်၊ ဒါမှ တခြား tab မှာ ပြင်ထားတာကို မထိပါဘူး။
  • 412 ကို ရင်ဆိုင်ရတဲ့အခါ UI က "ဒီ user ကို တခြားသူ ပြင်သွားပါပြီ၊ အသစ်ကို ကြည့်မလား" လို့ မေးပါတယ်။
  • Audit log မှာ ဘယ်သူက ဘယ် field ကို ဘာကနေ ဘာသို့ ပြောင်းလဲ မှတ်ပါတယ်၊ ဒါကြောင့် PATCH က ပြောင်းမယ့် field စာရင်း ရှိတာ အကျိုးရှိပါတယ်။

အမှားများ

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

PUT ကို partial body နဲ့ ပို့ပြီး PATCH ထင်ခြင်း

PUT { name } လုပ်ရင် PUT စည်းမျဉ်းအရ ကျန်တဲ့ field တွေ reset ဒါမှမဟုတ် 422 ဖြစ်ပါတယ်။ တစ်ချို့ field ကိုပဲ ပြောင်းချင်ရင် PATCH သုံးပါ၊ PUT အတွက်ဆိုရင် GET ရလာတဲ့ ပုံစံ တစ်ခုလုံးကို ပြင်ပြီး ပြန်ပို့ပါ။

Key ရှိမရှိ မစစ်ဘဲ truthiness စစ်ခြင်း

if (body.bio) လို့ စစ်ရင် null နဲ့ "" ကို ဖယ်လိုက်လို့ bio ကို ဖျက်လို့ မရတော့ပါဘူး။ 'bio' in body သို့ Object.hasOwn(body, "bio") နဲ့ key ရှိမရှိကို စစ်ပါ။

id နဲ့ role ကို body ကနေ လက်ခံခြင်း

Update endpoint ကလည်း mass assignment ဖြစ်နိုင်ပါတယ်။ member တစ်ယောက်က { "role": "admin" } ပို့ပြီး ကိုယ့်ကိုယ်ကို ရာထူးတိုးနိုင်ပါတယ်။ ရေးလို့ရတဲ့ field စာရင်းကို ပြတ်ပြတ်သားသား သတ်မှတ်ပါ၊ role ပြောင်းဖို့ လိုရင် admin သီးသန့် endpoint ထားပါ။

412 ကို If-Match ဖြုတ်ပြီး ပြန်ပို့ခြင်း

412 ကို ကျော်ဖို့ header ကို ဖြုတ်ပြီး ပြန်ပို့ရင် နောက်ဆုံးရေးတာက နိုင်တဲ့ အခြေအနေ ပြန်ရောက်ပြီး တခြားသူ ပြင်ချက် ပျောက်ပါတယ်။ ပြန်ဖတ်၊ merge လုပ်၊ ETag အသစ်နဲ့ ပို့ပါ။

Best Practices

Best practices

  • ပြင်ပရေးတဲ့ field စာရင်းကို ကုဒ်ထဲ တစ်နေရာတည်းမှာ ထားပြီး PUT, PATCH နှစ်ခုလုံးက အဲဒီစာရင်းကို မျှဝေသုံးပါ။
  • Response မှာ ETag အသစ်နဲ့ resource အပြည့်အစုံကို ပြန်ပါ၊ client က GET ထပ်မခေါ်ဘဲ နောက်ပြင်ချက်ကို ဆက်လုပ်နိုင်ပါတယ်။
  • လူ ကိုယ်တိုင် ပြင်တဲ့ data အတွက် If-Match ကို မဖြစ်မနေ ထားပြီး မပါရင် 428 ပြန်ပါ။

Mini challenge

applyUpdate ကို ကိုယ်တိုင် ရေးကြည့်ပါ

HTTP မလိုဘဲ applyUpdate(user, method, input, ifMatch) ကို ရေးပါ။ ifMatch ပေးထားပြီး "v" + user.version နဲ့ မတူရင် 412။ PATCH မှာ မပါတဲ့ field တွေကို မပြောင်းဘဲ null က ဖျက်ရမယ်။ PUT မှာ မပါတဲ့ bio က null ဖြစ်ရမယ်။ name သို့ email မပါ/အလွတ်ဆိုရင် 422 နဲ့ ပြဿနာရှိတဲ့ field နာမည်တွေ၊ မဟုတ်ရင် version + 1 နဲ့ 200 ပြန်ပါ။ id နဲ့ role ကို input ကနေ လျစ်လျူရှုပါ။

  • ifMatch ကို ပေးမှသာ စစ်ပြီး မတူရင် { status: 412 } ပြန်ပါ
  • PATCH: key ရှိမှ ပြောင်းပါ၊ PUT: ရေးလို့ရတဲ့ field တိုင်းအတွက် မပါရင် null
  • name/email မှားရင် { status: 422, fields: [...] }
  • အောင်မြင်ရင် version တစ်ခုတိုးပြီး id နဲ့ role မပြောင်းရ
apply-update.js
const WRITABLE = ["name", "email", "bio"];

function applyUpdate(user, method, input, ifMatch = null) {
  // TODO: 412 when ifMatch is given and is not "v" + user.version
  // TODO: PATCH keeps fields that are missing; "bio": null clears bio
  // TODO: PUT resets a missing writable field to null
  // TODO: ignore id and role from the input
  // TODO: 422 when name or email is missing or empty, else 200 with version + 1
}

ရလဒ်: ခြောက်ကြောင်း: PATCH name က bio ကို ထိန်းထားတယ်၊ PATCH null က bio ကို ဖျက်တယ်၊ PUT မှာ bio မပါရင် null၊ email မပါတဲ့ PUT က 422 email၊ PATCH role က မပြောင်းဘူး၊ stale request က 412။

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

next = { ...user } နဲ့ စပြီး WRITABLE ကို loop ပတ်ပါ၊ key in input နဲ့ ရှိမရှိကြည့်ပါ။ id နဲ့ role က WRITABLE ထဲ မပါတာကြောင့် ကိုယ်ဘာသာ ကာကွယ်ခံရပါတယ်။ ifMatch !== null ကိုစစ်ရင် If-Match မပါတဲ့ request ကို ခွင့်ပြုထားတာပါ။

အဖြေ ကြည့်ရန်
apply-update-solution.js
const WRITABLE = ["name", "email", "bio"];
const etagOf = (u) => '"v' + u.version + '"';

function applyUpdate(user, method, input, ifMatch = null) {
  if (ifMatch !== null && ifMatch !== etagOf(user)) {
    return { status: 412, error: "precondition_failed" };
  }
  const next = { ...user };
  for (const key of WRITABLE) {
    if (key in input) next[key] = input[key];
    else if (method === "PUT") next[key] = null;
  }
  const fields = [];
  if (typeof next.name !== "string" || !next.name.trim()) fields.push("name");
  if (typeof next.email !== "string" || !next.email.includes("@")) fields.push("email");
  if (fields.length) return { status: 422, error: "validation_failed", fields };
  return { status: 200, user: { ...next, version: user.version + 1 } };
}

const alice = {
  id: "u_1",
  name: "Alice",
  email: "alice@example.com",
  role: "admin",
  bio: "Maintainer",
  version: 1,
};

function show(label, r) {
  const u = r.user;
  const detail = u
    ? etagOf(u) + " name=" + u.name + " bio=" + u.bio + " role=" + u.role
    : r.error + (r.fields ? " " + r.fields.join(",") : "");
  console.log(label.padEnd(13), r.status, detail);
}
show("PATCH name", applyUpdate(alice, "PATCH", { name: "Alice K." }));
show("PATCH null", applyUpdate(alice, "PATCH", { bio: null }));
show("PUT, no bio", applyUpdate(alice, "PUT", { name: "Alice K.", email: alice.email }));
show("PUT, no email", applyUpdate(alice, "PUT", { name: "Alice K." }));
show("PATCH role", applyUpdate(alice, "PATCH", { role: "member", id: "u_9" }));
show("stale", applyUpdate(alice, "PATCH", { name: "X" }, '"v0"'));

Quick Quiz 1 / 3

User မှာ bio: "Maintainer" ရှိတယ်။ Client က PUT /v1/users/u_1 ကို { name: "Alice K.", email: "alice@example.com" } (bio မပါ) နဲ့ ပို့တယ်။ အဲဒီနောက် bio က ဘာဖြစ်သလဲ။

Quick Quiz 2 / 3

PATCH မှာ { "bio": null } ရဲ့ အဓိပ္ပာယ်က ဘာလဲ။

Quick Quiz 3 / 3

Client B က If-Match: "v3" နဲ့ PATCH ပို့တယ်၊ ဒါပေမဲ့ တခြား client က သိမ်းပြီးသားမို့ user က v4 ရောက်နေပြီ။ Server နဲ့ B က ဘာလုပ်ရမလဲ။

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

  • PUT က writable representation တစ်ခုလုံးကို အစားထိုး (မပါတာ reset)၊ PATCH က ပို့တဲ့ field ကိုပဲ ပြောင်း၊ null က ဖျက်၊ key မပါရင် မထိ။
  • id နဲ့ role လို server ပိုင် field တွေကို body ကနေ မယူပါနဲ့၊ merge ပြီးတဲ့ ရလဒ်ကို validate လုပ်ပါ၊ email ထပ်ရင် 409၊ user မရှိရင် 404။
  • ETag + If-Match နဲ့ lost update ကို ကာကွယ်ပါ: version မကိုက်ရင် 412၊ ပြီးရင် ပြန်ဖတ်၊ merge၊ ETag အသစ်နဲ့ ပြန်ပို့ပါ။
  • If-Match ကို optional ထားမလား မဖြစ်မနေ (428) ထားမလားက policy ပါ၊ လူပြင်တဲ့ data အတွက် မဖြစ်မနေ ထားတာ ပိုကောင်းပါတယ်။

RFC 9110 — HTTP Semantics — IETF

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

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

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

Update User | Thuta Learning