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

Create User

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

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

  • JSON POST ပို့ပြီး 201 response, Location header နဲ့ ဖန်တီးပြီးသား resource ကို ဖတ်နိုင်ဖို့
  • Validation failure တွေကို field တစ်ခုချင်း message ပါတဲ့ 422 အဖြစ် ပြန်ပြီး JSON ပျက်တာအတွက် 400 နဲ့ ခွဲခြားနိုင်ဖို့
  • Email ကို normalise လုပ်ပြီးနောက် ထပ်နေရင် 409 သုံးနိုင်ဖို့
  • Server က ရေးခွင့်ရှိတဲ့ field တွေကို allowlist လုပ်ပြီး body ထဲက id သို့ role ကို ဘာကြောင့် မယုံရလဲ ရှင်းပြနိုင်ဖို့

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

User ဖန်တီးခြင်းကို ရိုးရိုးလေး ပြောရရင်

User တစ်ယောက် ဖန်တီးတာက ရှေ့ကောင်တာမှာ အသင်းဝင်ပုံစံ ဖြည့်တာနဲ့ တူပါတယ်။ အချက်အလက် (name, email) ကို ပေးလိုက်တယ်၊ ဝန်ထမ်းက ပုံစံကို စစ်ပြီး record အသစ်တစ်ခု ရေးပေးတယ်၊ သင်မရွေးခဲ့တဲ့ နံပါတ်တစ်ခု ပေးတယ်၊ ပြီးတော့ "ဖန်တီးပြီးပါပြီ၊ သင့်ဖိုင်က /v1/users/u_2 မှာ ရှိပါတယ်" လို့ ပြောပါတယ်။ ပုံစံထဲမှာ မှားတာရှိရင် တိတ်တိတ်ပစ်မထားဘဲ field တစ်ခုချင်း မှတ်ချက်ရေးပြီး ပြန်ပေးပါတယ်။

HTTP ဘာသာနဲ့ပြောရင် JSON body ပါတဲ့ POST /v1/users ကို ပို့ပါတယ်။ အောင်မြင်ရင် server က 201 Created ပြန်ပြီး resource အသစ်ရဲ့ URL ကို Location header ထဲ ထည့်ကာ ကိုယ်တိုင်ထုတ်ပေးလိုက်တဲ့ id ပါတဲ့ user အသစ်ကို body ထဲမှာ ပြန်ပေးပါတယ်။

Problem → Why → Solution

ပြဿနာ: client ပို့သမျှကို သိမ်းလိုက်တဲ့ endpoint

Create endpoint ရဲ့ ပထမ version အများစုက လာသမျှ JSON ကို သိမ်းလိုက်ပါတယ်။ {"name": "Mallory", "email": "m@example.com", "role": "admin"} ပို့တဲ့ client က object ကို database ထဲ တိုက်ရိုက်ထည့်လိုက်လို့ ကိုယ့်ကိုယ်ကို administrator လုပ်လိုက်နိုင်ပါတယ်။ အဲဒီ endpoint ကပဲ အောင်မြင်ရင် 200 ပြန်တယ်၊ email မပါရင် stack trace ပါတဲ့ 500 ပြန်တယ်၊ Bob@Example.com နဲ့ bob@example.com ကို account နှစ်ခု သိမ်းပေးပါတယ်။ ဒီအချက်တစ်ခုချင်းစီက bug မတူပါဘူး: privilege escalation, အသုံးမကျတဲ့ error နဲ့ duplicate ပါ။

save-everything.js
// Saves whatever the client sends
app.post("/v1/users", async (req, res) => {
  const user = await db.users.insert(req.body); // id, role, anything
  res.json(user);                               // 200, no Location header
});

စည်းမျဉ်းတွေကို server က ပိုင်ရမယ်

Request body ထဲက အရာအားလုံးကို client က ရွေးတာပါ၊ အဲဒီ client က တိုက်ခိုက်သူ ရေးထားတဲ့ script လည်း ဖြစ်နိုင်ပါတယ်။ ဘယ် field ကို client က သတ်မှတ်ခွင့်ရှိလဲ (allowlist)၊ ဘာက valid လဲ၊ response က ဘာပြောမလဲဆိုတာ server က ဆုံးဖြတ်ရပါမယ်။ ကိုယ့် form က validate လုပ်ပြီးသားဆိုရင်တောင် ဒါကို server မှာ လုပ်ရပါမယ်၊ ကိုယ့် form ကိုပဲ သုံးရမယ်လို့ ဘယ်သူမှ မတားထားလို့ပါ။

Core concept: collection ထဲကို POST လုပ်ပြီး ရလဒ်ကို ညွှန်ပြခြင်း

POST /v1/users ဆိုတာ "users collection ထဲကို အဖွဲ့ဝင်အသစ် ထည့်ပါ" လို့ ဆိုလိုတာပါ။ Client က resource အသစ်ရဲ့ URL ဒါမှမဟုတ် id ကို မရွေးရလို့ POST ကို collection ဆီပို့ပြီး resource က ဘယ်မှာရှိလဲဆိုတာ server က ပြန်ပြောပါတယ်။ အောင်မြင်ရင် 201 Created ပါ၊ Location header မှာ URL အသစ်ပါပြီး body ထဲမှာ resource အပြည့်အစုံ ပါလေ့ရှိလို့ client က GET ထပ်ခေါ်စရာ မလိုပါဘူး။ POST က idempotent မဟုတ်ပါဘူး: server က မကာကွယ်ထားရင် request တူတူကို နှစ်ကြိမ်ပို့ရင် user နှစ်ယောက် ဖြစ်သွားမှာပါ။

Validation က အလွှာလိုက် ကျရှုံးနိုင်ပြီး အလွှာတစ်ခုစီမှာ status မတူပါဘူး။ Body က valid JSON မဟုတ်ရင် ဒါမှမဟုတ် Content-Type မှားရင် server က request ကို ဖတ်တောင် မရလို့ 400 Bad Request ပါ။ Parse ရပေမဲ့ တန်ဖိုးတစ်ခုခု လက်မခံနိုင်ရင် (name အလွတ်၊ email ပုံစံမှား) 422 ပြန်ပြီး ပြဿနာအားလုံးကို field တစ်ခုချင်း message နဲ့ တစ်ခါတည်း စာရင်းပြပါ၊ ဒါမှ user က form တစ်ခုလုံးကို round trip တစ်ခုတည်းနဲ့ ပြင်နိုင်မှာပါ။ တန်ဖိုးတွေ မှန်ပေမဲ့ ရှိပြီးသား data နဲ့ တိုက်နေရင် (email က တခြား user ပိုင်ပြီးသား) 409 Conflict ပါ။ နှိုင်းယှဉ်ခင် normalise အရင်လုပ်ပါ: whitespace ဖြတ်ပြီး email ကို lowercase လုပ်ပါ၊ မဟုတ်ရင် Bob@Example.com နဲ့ bob@example.com က account နှစ်ခု ဖြစ်သွားပါလိမ့်မယ်။

အခြေအနေStatuserror.code
ဖန်တီးပြီး201(body မှာ user၊ Location header)
Body က valid JSON မဟုတ်400invalid_json
name မပါ၊ email မမှန်422validation_failed + fields
Email သုံးပြီးသား409email_taken

Record အသစ်ကို ခွင့်ပြုထားတဲ့ field စာရင်း (name, email, bio) ကနေ ဆောက်ပါ၊ ကျန်တာအားလုံးကို server ဘက်က တန်ဖိုးပေးပါ: id ကို server က ထုတ်ပြီး role က "member" ပါ။ Body ထဲက role: "admin" လို အပိုတွေကို ဒီမှာ လျစ်လျူရှုပါတယ်၊ တင်းကျပ်တဲ့ API တချို့က 422 နဲ့ ငြင်းပါတယ်။ ဘယ်လိုပဲဖြစ်ဖြစ် protected field ကို client ကဘယ်တော့မှ မရွေးနိုင်ရပါဘူး။ API က password လက်ခံရင် argon2 သို့ bcrypt လို password အတွက်ပဲ ဖန်တီးထားတဲ့ algorithm နဲ့ hash လုပ်ပြီး ပြန်မပေးရပါဘူး။ Unique check နဲ့ insert ကိုလည်း တစ်ခုတည်းသော atomic လုပ်ငန်းအဖြစ် (transaction သို့ database unique constraint) လုပ်ပါ၊ မဟုတ်ရင် တစ်ပြိုင်နက် ရောက်လာတဲ့ request နှစ်ခုက "သုံးပြီးသားလား" စစ်ဆေးမှုကို နှစ်ခုလုံး ဖြတ်သွားနိုင်ပါတယ်။

ဖြည့်၊ စစ်၊ သိမ်း၊ ညွှန်ပြ
  1. Client က JSON body နဲ့ POST ပို့
  2. Server စစ်: 400, 422 ဒါမှမဟုတ် 409
  3. Server က record နဲ့ id ကို ဆောက်
  4. 201 Created + Location + user အသစ်

Client က တန်ဖိုးတွေကို အဆိုပြုတာပါ၊ id, role နဲ့ request လက်ခံနိုင်မနိုင်ကိုတော့ server က ဆုံးဖြတ်ပါတယ်။

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

text
POST /v1/<collection>
Content-Type: application/json

{ <writable fields only> }

201 Created
Location: /v1/<collection>/<new id>
{ <the created resource, including server-set fields> }

Request မှာ client ရေးခွင့်ရှိတဲ့ field တွေပဲ ပါပါတယ်၊ response မှာတော့ server ထုတ်ပေးတဲ့ id လို field တွေပါ ပါတဲ့ resource အပြည့်အစုံနဲ့ ရောက်ရှိနိုင်တဲ့ URL ပါပါတယ်။

Worked example: user ဖန်တီးပြီး Location ကို လိုက်ခြင်း

ဒီ sample က random local port တစ်ခုမှာ users API သေးသေးလေး run ပါတယ်။ Alice (u_1, admin) နဲ့ စပါတယ်၊ ပြီးတော့ call ခြောက်ခု လုပ်ပြပါတယ်: 201 နဲ့ Location header ပြန်တဲ့ POST၊ အဲဒီ Location ကို လိုက်တဲ့ GET၊ role: admin ကို ခိုးထည့်ဖို့ ကြိုးစားတာ (လျစ်လျူရှုခံရတယ်)၊ field message နှစ်ခုပါတဲ့ 422၊ capitalisation မတူတဲ့ email တူနဲ့ 409 နဲ့ JSON မဟုတ်တဲ့ body။ Run တိုင်း output တူပါတယ်။

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

// The users API (stands in for https://api.example.com/v1/users)
const users = new Map();
users.set("u_1", {
  id: "u_1",
  name: "Alice",
  email: "alice@example.com",
  role: "admin",
  bio: null,
});
let nextId = 2;

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 }) } });
const looksLikeEmail = (s) => typeof s === "string" && /^[^@ ]+@[^@ ]+[.][^@ ]+$/.test(s);

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;
  }
}

const server = http.createServer(async (req, res) => {
  const { pathname } = new URL(req.url, "http://localhost");
  const [, , resource, id] = pathname.split("/");
  if (resource === "users" && req.method === "GET" && id) {
    const user = users.get(id);
    if (!user) return fail(res, 404, "user_not_found", "No user " + id);
    return send(res, 200, user);
  }
  if (resource !== "users" || req.method !== "POST" || id) {
    return fail(res, 404, "not_found", "No such route");
  }

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

  // Validate everything, then report every problem at once
  const fields = {};
  const name = typeof input.name === "string" ? input.name.trim() : "";
  if (!name) fields.name = "is required";
  if (!looksLikeEmail(input.email)) fields.email = "must be a valid email address";
  if (Object.keys(fields).length) {
    return fail(res, 422, "validation_failed", "One or more fields are invalid", fields);
  }

  // Normalise first, then check uniqueness
  const email = input.email.trim().toLowerCase();
  if ([...users.values()].some((u) => u.email === email)) {
    return fail(res, 409, "email_taken", "A user with this email already exists");
  }

  // Allowlist: the client can set name, email and bio. id and role are ours.
  const bio = input.bio ?? null;
  const user = { id: "u_" + nextId++, name, email, role: "member", bio };
  users.set(user.id, user);
  send(res, 201, user, { Location: "/v1/users/" + user.id });
});
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 post(payload) {
  const res = await fetch(base + "/v1/users", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: typeof payload === "string" ? payload : JSON.stringify(payload),
  });
  return { res, data: await res.json() };
}

const bob = await post({ name: "Bob", email: "Bob@Example.com", bio: "Loves APIs" });
console.log(bob.res.status, bob.res.headers.get("location"));
console.log(JSON.stringify(bob.data));

const again = await fetch(base + bob.res.headers.get("location"));
console.log("follow Location:", again.status, (await again.json()).name);

const carol = await post({ name: "Carol", email: "carol@example.com", role: "admin" });
console.log(carol.res.status, "role:", carol.data.role, "(the client asked for admin)");

const bad = await post({ name: "  ", email: "not-an-email" });
console.log(bad.res.status, bad.data.error.code, JSON.stringify(bad.data.error.fields));

const dup = await post({ name: "Bobby", email: "BOB@example.com" });
console.log(dup.res.status, dup.data.error.code);

const broken = await post("{ name: Bob");
console.log(broken.res.status, broken.data.error.code);
server.close();

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

  1. Read the body safelyreturn value?.constructor === Object ? value : null; // plain objects only

    JSON.parse က null, array, ဂဏန်းတွေကိုလည်း valid လို့ ပြန်နိုင်လို့ သာမန် object ဖြစ်မှ လက်ခံပါတယ်။ ဒီစစ်ဆေးမှု မရှိရင် body က null ဖြစ်တဲ့အခါ input.name မှာ crash ဖြစ်မှာပါ။

  2. 400 before anything elseif (!input) return fail(res, 400, "invalid_json", "Body must be a JSON object");

    Body ကို ဖတ်လို့မရရင် field ကို စစ်ဖို့ အဓိပ္ပာယ်မရှိတော့လို့ ဒီမှာ ချက်ချင်း 400 ပြန်ပါတယ်။

  3. 422 with one message per fieldif (!name) fields.name = "is required";

    Field တစ်ခု မှားတိုင်း fields object ထဲ ထည့်ပြီး မရပ်ဘဲ ဆက်စစ်ပါတယ်။ ဒါကြောင့် bad ဆိုတဲ့ request က name နဲ့ email နှစ်ခုလုံးအတွက် message တစ်ပြိုင်နက် ရပါတယ်။

  4. Normalise, then compareconst email = input.email.trim().toLowerCase();

    BOB@example.com ကို bob@example.com အဖြစ် ပြောင်းပြီးမှ နှိုင်းယှဉ်လို့ capitalisation ပြောင်းတာနဲ့ duplicate စစ်ဆေးမှုကို မကျော်နိုင်ပါဘူး။ သိမ်းတဲ့ တန်ဖိုးကလည်း lowercase ပါပဲ။

  5. 409 for a conflictreturn fail(res, 409, "email_taken", "A user with this email already exists");

    တန်ဖိုးတွေ မှန်တယ်၊ ဒါပေမဲ့ ရှိပြီးသား data နဲ့ တိုက်နေတာမို့ 422 မဟုတ်ဘဲ 409 ပါ။ Client က တခြား email ရွေးရမှာပါ။

  6. Allowlist, 201 and Locationsend(res, 201, user, { Location: "/v1/users/" + user.id });

    user object ကို name, email, bio နဲ့ server ထုတ်တဲ့ id, role တို့နဲ့သာ ဆောက်ထားလို့ carol ရဲ့ role: admin က မပါပါဘူး။ Response က 201 နဲ့ Location ပါပါတယ်။

You should see
201 /v1/users/u_2
{"id":"u_2","name":"Bob","email":"bob@example.com","role":"member","bio":"Loves APIs"}
follow Location: 200 Bob
201 role: member (the client asked for admin)
422 validation_failed {"name":"is required","email":"must be a valid email address"}
409 email_taken
400 invalid_json
POST /v1/users ကို server က ကိုင်တွယ်ပုံ
  1. Body ကို ဖတ်ပြီး JSON object ဟုတ်မဟုတ် စစ်
  2. name, email ကို validate လုပ်
  3. Email ကို normalise လုပ်ပြီး ထပ်မထပ် စစ်
  4. Allowlist နဲ့ record ဆောက်ပြီး 201 ပြန်

အဆင့်အားလုံး ကျော်

201 Created with Location and the new user

အဆင့်တစ်ခု မအောင်

400, 422 or 409 with a JSON error body and nothing is saved

ဒီအခန်းမှာ သုံးမယ့် users resource

နောက်သင်ခန်းစာသုံးခု (read, update, delete) မှာလည်း resource တူကို ဆက်သုံးပါမယ်၊ ဒါကြောင့် ကတိတွေကို ဒီမှာ တစ်ခါတည်း သတ်မှတ်ထားပါ။ Error ပုံစံကလည်း အမြဲတူပါတယ်: { "error": { "code", "message", "fields"? } }။ Client ဘက်က error handler တစ်ခုတည်းနဲ့ endpoint တိုင်းကို ကိုင်တွယ်နိုင်တာ ဒီကြောင့်ပါ။

Fieldဘယ်သူ သတ်မှတ်လဲစည်းကမ်း
idServeru_ နောက်မှာ ဂဏန်း၊ ဘယ်တော့မှ မပြောင်း
nameClientလိုအပ်၊ အလွတ်မဖြစ်ရ
emailClientလိုအပ်၊ valid၊ unique၊ lowercase နဲ့ သိမ်း
roleServerဖန်တီးချိန်မှာ member၊ client မရေးနိုင်
bioClientoptional၊ မရှိရင် null

curl နဲ့ ကိုယ်တိုင် စမ်းကြည့်ခြင်း

တကယ့် API တစ်ခုကို curl နဲ့ ခေါ်တဲ့အခါ -i flag က response header တွေကိုပါ ပြပါတယ်၊ Location ကို မြင်ဖို့ အရေးကြီးပါတယ်။ Windows PowerShell မှာ single quote ပြဿနာရှိနိုင်လို့ Git Bash သို့ Linux/macOS terminal မှာ စမ်းလို့ အသင့်တော်ဆုံးပါ။ api.example.com က ဥပမာ domain ပါ၊ သင့် API ရဲ့ URL နဲ့ အစားထိုးပါ။

bash
curl -i -X POST https://api.example.com/v1/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Bob","email":"bob@example.com"}'

# HTTP/1.1 201 Created
# Location: /v1/users/u_2
# {"id":"u_2","name":"Bob","email":"bob@example.com","role":"member","bio":null}

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

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

Sign-up ကို handle လုပ်တဲ့ create endpoint ကို ဘာမဆို လုပ်နိုင်တဲ့ လူ (အင်တာနက်တစ်ခုလုံး) ဆီက ခေါ်ခံရပါတယ်၊ ဒါကြောင့် abuse ကို ကာကွယ်ဖို့ rate limit နဲ့ CAPTCHA တွေကိုပါ ထည့်လေ့ရှိပါတယ်။ ဒီအခန်းက pattern ကို Stripe, GitHub လို API တွေမှာလည်း တွေ့ရပါတယ်: resource အသစ်ကို 201 နဲ့ ပြန်ပေးတာ၊ field အလိုက် validation message တွေ ပေးတာတွေပါ။ Provider တစ်ခုချင်းစီက 422 ကို သုံးသလား၊ 400 ကို သုံးသလားဆိုတာ မတူနိုင်လို့ docs ကို စစ်ပါ။

  • Frontend form က 422 ရဲ့ fields ကို ဖတ်ပြီး input တစ်ခုချင်းစီဘေးမှာ message ပြပါတယ်၊ 409 ကို "ဒီ email နဲ့ account ရှိပြီးသားပါ" လို့ ပြပါတယ်။
  • Test တွေက valid request, name မပါတာ, email မမှန်တာ, email ထပ်တာ, role ခိုးထည့်တာနဲ့ body က JSON မဟုတ်တာ အားလုံးကို စမ်းပါတယ်။
  • Retry ခံရနိုင်တဲ့ client တွေအတွက် Idempotency-Key header ကို support လုပ်တဲ့ API တွေလည်း ရှိပါတယ်၊ ဒါမှ network ပြတ်ပြီး ပြန်ပို့ရင် user နှစ်ခု မဖြစ်ပါဘူး။

အမှားများ

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

req.body ကို database ထဲ တိုက်ရိုက်ထည့်ခြင်း

ORM ရဲ့ create ဆီ body ကို အကုန်ပို့ရင် role: "admin", id ဒါမှမဟုတ် internal flag တွေကို client က ရေးနိုင်သွားပါတယ် (mass assignment)။ ခွင့်ပြုတဲ့ field တွေကို အမည်နဲ့ ရွေးထုတ်ပါ။

Error တစ်ခုချင်းပဲ ပြန်ခြင်း

ပထမ မှားတာတစ်ခုမှာ ရပ်ပြီး ပြန်ရင် user က form ကို သုံးလေးကြိမ် ပြန်ပို့ရပါလိမ့်မယ်။ field အားလုံးကို စစ်ပြီး fields object တစ်ခုတည်းနဲ့ ပြန်ပါ။

Normalise မလုပ်ဘဲ uniqueness စစ်ခြင်း

Bob@Example.com နဲ့ bob@example.com ကို မတူဘူးလို့ ယူဆရင် account နှစ်ခု ဖြစ်ပြီး password reset email တွေ မှားပို့မိနိုင်ပါတယ်။ trim နဲ့ lowercase လုပ်ပြီးမှ နှိုင်းယှဉ်ပါ၊ database ထဲမှာလည်း unique constraint ထားပါ။

200 ပြန်ပြီး Location မထည့်ခြင်း

အောင်မြင်တဲ့ create ကို 200 နဲ့ ပြန်ရင် client က resource အသစ် ဖန်တီးပြီးလား၊ ရှိပြီးသားကို ပြန်ပေးတာလားဆိုတာ မခွဲနိုင်ပါဘူး။ 201 နဲ့ Location ကို သုံးပါ။

Best Practices

Best practices

  • Validation စည်းမျဉ်းတွေကို တစ်နေရာထဲ ထားပါ၊ frontend ရော backend ရော ထိုနေရာကပဲ စည်းမျဉ်းကို မျှဝေသုံးပါ။
  • Response ထဲက resource ကို နောက်ပိုင်း GET /v1/users/u_2 ပြန်ဖတ်ရင် ရမယ့် ပုံစံအတိုင်းပဲ ထားပါ။
  • Error code တွေကို တည်ငြိမ်စွာထားပါ၊ message စာသားကိုတော့ နောက်မှ ပြင်လို့ရပါတယ်။

Mini challenge

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

HTTP server မလိုဘဲ createUser(users, body) ကို ရေးပါ။ { status, headers, body } ကို ပြန်ပေးရမယ် (ဘာမှ ပို့စရာ မလိုပါဘူး)။ body က plain object မဟုတ်ရင် 400၊ field မှားရင် field တစ်ခုချင်း message ပါတဲ့ 422၊ lowercase လုပ်ထားတဲ့ email ထပ်ရင် 409၊ ကျန်ရင် allowlist field တွေနဲ့ user ဆောက်ပြီး 201 နဲ့ Location ပြန်ပါ။

  • Plain object မဟုတ်ရင် (array အပါအဝင်) 400 invalid_json
  • name လိုအပ်၊ email ပုံစံမှန်ရမယ်၊ မှားရင် 422 နဲ့ fields
  • email ကို trim, lowercase လုပ်ပြီး ထပ်ရင် 409 email_taken
  • role က အမြဲ member၊ body ထဲက role ကို လျစ်လျူရှု၊ Location: /v1/users/<id>
create-user.js
const users = [
  { id: "u_1", name: "Alice", email: "alice@example.com", role: "admin", bio: null },
];

function validate(body) {
  // TODO: return an object with one message per invalid field (empty when valid)
}

function createUser(users, body) {
  // TODO: 400 when body is not a plain object
  // TODO: 422 with { error: { code, message, fields } } when validate() finds problems
  // TODO: 409 when the lowercased email is already taken
  // TODO: otherwise build the user from allowed fields only and answer 201 + Location
  // Return { status, headers, body }; nothing is sent over a network here
}

ရလဒ်: Output လေးကြောင်း: ပထမတစ်ကြောင်းက 201 နဲ့ Location ၊ role member, ကျန်သုံးကြောင်းက 422, 409, 400 နဲ့ error code တွေပါ။

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

Error response ဆောက်တဲ့ helper သေးသေးလေး တစ်ခုထားရင် status လေးမျိုးလုံးမှာ ပြန်သုံးလို့ရပါတယ်။ body?.constructor !== Object က array, null, string ကို တစ်ခါတည်း ဖယ်ပေးပါတယ်။ id ကို users.length + 1 နဲ့ ဆောက်လို့ ရပါတယ်။

အဖြေ ကြည့်ရန်
create-user-solution.js
const users = [
  { id: "u_1", name: "Alice", email: "alice@example.com", role: "admin", bio: null },
];

const problem = (status, code, message, fields) => ({
  status,
  headers: {},
  body: { error: { code, message, ...(fields && { fields }) } },
});

function validate(body) {
  const fields = {};
  if (typeof body.name !== "string" || !body.name.trim()) fields.name = "is required";
  const email = typeof body.email === "string" ? body.email.trim() : "";
  if (!email.includes("@") || !email.split("@")[1].includes(".")) {
    fields.email = "must be a valid email address";
  }
  return fields;
}

function createUser(users, body) {
  if (body?.constructor !== Object) {
    return problem(400, "invalid_json", "Body must be a JSON object");
  }
  const fields = validate(body);
  if (Object.keys(fields).length) {
    return problem(422, "validation_failed", "Invalid fields", fields);
  }
  const email = body.email.trim().toLowerCase();
  if (users.some((u) => u.email === email)) {
    return problem(409, "email_taken", "Email already used");
  }
  const user = {
    id: "u_" + (users.length + 1),
    name: body.name.trim(),
    email,
    role: "member",
    bio: body.bio ?? null,
  };
  users.push(user);
  return { status: 201, headers: { Location: "/v1/users/" + user.id }, body: user };
}

function show(result) {
  const b = result.body;
  const detail = b.error
    ? b.error.code + " " + JSON.stringify(b.error.fields ?? {})
    : b.id + " " + b.email + " " + b.role;
  console.log(result.status, result.headers.Location ?? "-", detail);
}

show(createUser(users, { name: "Dana", email: "Dana@Example.com", role: "admin" }));
show(createUser(users, { name: "", email: "dana" }));
show(createUser(users, { name: "Dan", email: "DANA@example.com" }));
show(createUser(users, [1, 2]));

Quick Quiz 1 / 3

ဘယ် response က အောင်မြင်တဲ့ POST /v1/users အတွက် အမှန်ကန်ဆုံး ဖြစ်သလဲ။

Quick Quiz 2 / 3

Client က { "name": "Bob", "email": "bob@example" } ကို ပို့ပြီး JSON တော့ မှန်ပါတယ်။ ဘယ် status အသင့်တော်ဆုံးလဲ။

Quick Quiz 3 / 3

alice@example.com ရှိပြီးသား။ Client က ALICE@Example.com နဲ့ user အသစ်ဖန်တီးတယ်။ Server ကို normalise မလုပ်ဘဲ တိုက်ရိုက်နှိုင်းယှဉ်ရင် ဘာဖြစ်မလဲ။

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

  • POST ကို collection (/v1/users) ဆီပို့ပါ၊ အောင်မြင်ရင် 201 Created၊ Location header နဲ့ resource အပြည့်အစုံ ပြန်ပါ။
  • 400 = body ဖတ်မရ၊ 422 = တန်ဖိုးမှား (field တစ်ခုချင်း message)၊ 409 = ရှိပြီးသား data နဲ့ တိုက်နေ။
  • Email ကို trim + lowercase လုပ်ပြီးမှ နှိုင်းယှဉ်ပါ၊ unique check နဲ့ insert ကို atomic လုပ်ပါ။
  • Allowlist field တွေကိုပဲ client က ရေးခွင့်ပေးပါ၊ id နဲ့ role ကို server က ထုတ်ပါ။

RFC 9110 — HTTP Semantics — IETF

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

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

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

Create User | Thuta Learning