ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Practice Set 1 က page တွေ ဘယ်လို ပေါ်လဲ ဆိုတာပါ။ ဒီ Set 2 ကတော့ data ဘယ်လို ဝင်လာလဲ၊ ဘယ်လို ပြောင်းလဲ၊ ပြောင်းပြီးရင် cache ကို ဘယ်လို ပြန်ရှင်းလဲ ဆိုတာပါ။ Quote (ဆိုရိုးစကား) စုတဲ့ app သေးသေးလေး တစ်ခုပေါ်မှာ task လေးခု လုပ်ပါမယ်။
စာကြည့်တိုက်နဲ့ ဥပမာပေးရရင် Route Handler က စာအုပ်ငှားတဲ့ ကောင်တာ၊ Server Action က အသင်းဝင်လျှောက်လွှာ form၊ cache tag ကတော့ "ဒီ shelf ကို ပြန်စီ" လို့ ကပ်ထားတဲ့ စာရွက်ပါ။ Task တိုင်းမှာ အလုပ်ဖြစ်တဲ့ case နဲ့ မှားတဲ့ input case နှစ်ခုလုံးကို စမ်းရပါမယ်။
Problem → Why → Solution
ပြဿနာ: happy path ပဲ စမ်းထားတဲ့ API
ပထမ draft မှာ POST handler က await request.json() ကို try/catch မပါဘဲ ခေါ်ပြီး error ဖြစ်ရင် 200 status နဲ့ပဲ { error } ကို ပြန်ပေးပါတယ်။ Browser ကနေ စမ်းတော့ အကုန်ကောင်းနေပါတယ်။
တကယ့် client တွေ ရောက်လာတော့ ပြဿနာ နှစ်ခု ပေါ်ပါတယ်။ JSON မဟုတ်တဲ့ body ပို့လိုက်ရင် request.json() က throw လုပ်ပြီး server error (500) ဖြစ်သွားပါတယ်။ Validation error ကလည်း 200 နဲ့ ပြန်လာလို့ client က response.ok ကို စစ်ပြီး "အောင်မြင်တယ်" လို့ ထင်ကာ form ကို ရှင်းပစ်လိုက်ပါတယ်။
export async function POST(request: Request) {
const body = await request.json(); // throws on "not json" -> 500
if (typeof body.text !== "string" || body.text.length <= 3) {
return Response.json({ error: "text is too short" }); // status 200!
}
quotes.push({ text: body.text, author: body.author ?? "Unknown" });
return Response.json({ ok: true }); // should be 201
}Status code က API ရဲ့ စာချုပ်ပါ
API ကို ခေါ်တဲ့ code က body ကို မဖတ်ခင် status ကိုပဲ အရင် ကြည့်လေ့ရှိပါတယ်။ 2xx က အောင်မြင်တယ်၊ 4xx က client ဘက်က မှားတယ်၊ 5xx က server ဘက်က ပျက်တယ်လို့ ဆိုလိုပါတယ်။ Status မှားရင် client တွေ အကုန်လုံး မှားတဲ့ ဆုံးဖြတ်ချက် ချပါတယ်။
Core concept: task လေးခုရဲ့ နောက်ကွယ်က စည်းမျဉ်း
Practice Set 1 ရဲ့ project ကိုပဲ ဆက်သုံးနိုင်သလို project အသစ်လည်း ဖွင့်နိုင်ပါတယ်။ Task တစ်ခုစီအတွက် "ဘယ် input က ဘယ် status ဒါမှမဟုတ် state ကို ပြန်ရမလဲ" ဆိုတဲ့ စာရင်းကို အရင်ရေးပါ။ အဲဒီ စာရင်းက ကိုယ့်ရဲ့ test plan ဖြစ်ပြီး code ရေးပြီးရင် တစ်ကြောင်းချင်း စစ်ရမှာပါ။ အောက်က table မှာ task တစ်ခုစီရဲ့ အနည်းဆုံး case တွေ ပါပါတယ်။
| Task | ရေးရမယ့်အရာ | စစ်ရမယ့် case |
|---|---|---|
| 1 | app/api/quotes/route.ts ရဲ့ GET | 200 နဲ့ quote array |
| 2 | POST + validation | 201 / text တိုရင် 400 / JSON မဟုတ်ရင် 400 |
| 3 | subscribe Server Action + form | Email မှား / အောင်မြင် / ထပ်နေ |
| 4 | Cache tag + invalidation | Mutation ပြီးရင် data အသစ် ပေါ် |
Route Handler = Request ဝင်၊ Response ထွက်
route.ts ထဲမှာ GET၊ POST လို HTTP method နာမည်နဲ့ function တွေ export လုပ်ပါတယ်။ Web standard Request ကို ရပြီး Response ကို ပြန်ပေးရုံပါ။ Next.js သီးသန့် object မလိုလို့ Node 22 မှာ new Request() နဲ့ တိုက်ရိုက်ခေါ်ပြီး test လုပ်လို့ရပါတယ်။ Response.json(data, { status }) နဲ့ status ကို ကိုယ်တိုင် သတ်မှတ်ပါ။
Server Action + useActionState
useActionState(action, initialState) နဲ့ ချိတ်တဲ့ action က (prevState, formData) ကို ရပြီး state အသစ်ကို return ပြန်ပါတယ်။ Hook က [state, formAction, isPending] ကို ပေးပါတယ်။ Tutorial အဟောင်းတွေမှာ တွေ့ရတဲ့ react-dom ရဲ့ useFormState ကို React 19 မှာ react package ထဲက useActionState နဲ့ အစားထိုးထားပါတယ်။
Cache tag ကို ဘယ်မှာ ကပ်၊ ဘယ်မှာ ဖြုတ်
Tag ကို cache လုပ်ထားတဲ့ data မှာပဲ ကပ်လို့ ရပါတယ်။ Caching lesson လို "use cache" function ထဲမှာ cacheTag("quotes") နဲ့ ကပ်နိုင်သလို fetch(url, { cache: "force-cache", next: { tags: ["quotes"] } }) နဲ့လည်း ကပ်နိုင်ပါတယ်။ Server Action ထဲမှာ updateTag("quotes") က ချက်ချင်း expire လုပ်လို့ user က သူ့ရဲ့ ပြောင်းလဲမှုကို ချက်ချင်း မြင်ရပါတယ်။ Webhook လို Route Handler ထဲမှာတော့ updateTag ကို ခေါ်ခွင့်မရှိလို့ revalidateTag("quotes", "max") ကို သုံးပါ။
- Request/FormData ဝင်လာ
- Server မှာ type နဲ့ value ကို စစ်
- မှန်ကန်တဲ့ status/state ပြန်ပေး
- ပြောင်းသွားတဲ့ data ရဲ့ tag ကို ရှင်း
အဆင့်လေးဆင့်ထဲက တစ်ဆင့် ကျန်ခဲ့ရင် bug ဖြစ်ပါတယ်။ အများဆုံး ကျန်ခဲ့တတ်တာက ဒုတိယနဲ့ စတုတ္ထ အဆင့်ပါ။
အခြေခံ ပုံစံ: method handler
// app/api/<resource>/route.ts
export async function POST(request: Request) {
let body: unknown;
try { body = await request.json(); }
catch { return Response.json({ error: "Invalid JSON" }, { status: 400 }); }
if (!isValid(body)) return Response.json({ error: "..." }, { status: 400 });
const saved = await save(body);
return Response.json(saved, { status: 201 });
}Parse မအောင်မြင်ရင် 400၊ validation မအောင်မြင်ရင် 400၊ အသစ်ဖန်တီးပြီးရင် 201 ပြန်ပေးပါ။ GET ကတော့ data ကို 200 နဲ့ ပြန်ပေးပါတယ်။
Task 1-2: route handler ကို Node မှာ test လုပ်မယ်
အောက်က file ရဲ့ အပေါ်ပိုင်းက Next.js project ထဲက app/api/quotes/route.ts အတိုင်းပါ။ အောက်ဆုံးက test အပိုင်းက Next.js လုပ်သလိုပဲ new Request() တစ်ခု ဆောက်ပြီး POST() ကို တိုက်ရိုက် ခေါ်ပါတယ်။ Project ထဲ ထည့်တဲ့အခါ test အပိုင်းကို ဖယ်ပြီး curl -X POST -d '{"text":"hi"}' http://localhost:3000/api/quotes -i နဲ့ စစ်ပါ။
// app/api/quotes/route.ts - Route Handlers are plain Web Request -> Response
// functions, so this file runs in Node as-is (the test calls are at the bottom).
type Quote = { text: string; author: string };
const quotes: Quote[] = [
{ text: "Make it work, make it right, make it fast.", author: "Kent Beck" },
];
export async function GET() {
return Response.json(quotes);
}
export async function POST(request: Request) {
let body: unknown;
try {
body = await request.json();
} catch {
return Response.json({ error: "Body must be JSON" }, { status: 400 });
}
const { text, author } = (body ?? {}) as Partial<Record<string, unknown>>;
if (typeof text !== "string" || text.trim().length <= 3) {
const error = "text must be longer than 3 characters";
return Response.json({ error }, { status: 400 });
}
const quote: Quote = {
text: text.trim(),
author: typeof author === "string" && author.trim() ? author.trim() : "Unknown",
};
quotes.push(quote);
return Response.json(quote, { status: 201 });
}
// --- quick test: call the handlers the way Next.js would ---
const post = (body: string) =>
POST(new Request("http://localhost/api/quotes", { method: "POST", body }));
async function main() {
const bodies = [
JSON.stringify({ text: "Simple is better than complex." }),
JSON.stringify({ text: "hi" }),
"not json",
];
for (const body of bodies) {
const res = await post(body);
console.log(res.status, JSON.stringify(await res.json()));
}
const list = await GET();
const all: Quote[] = await list.json();
console.log(list.status, all.length, "quotes");
}
main();Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Parse failures are the client's fault
return Response.json({ error: "Body must be JSON" }, { status: 400 });request.json() က invalid JSON မှာ throw လုပ်ပါတယ်။ ဖမ်းမထားရင် 500 ဖြစ်ပြီး server ပျက်တယ်လို့ အဓိပ္ပာယ်ရပါတယ်။ ဖမ်းပြီး 400 ပြန်ပေးတော့ client ဘက်က ပြင်ရမယ်ဆိုတာ ရှင်းပါတယ်။
- Treat the body as unknown
const { text, author } = (body ?? {}) as Partial<Record<string, unknown>>;Client က ဘာမဆို ပို့နိုင်လို့ field တိုင်းကို unknown အဖြစ် ယူပြီး typeof နဲ့ စစ်ပါတယ်။ body ?? {} က null ပို့လာတဲ့ case ကို ကာကွယ်ပါတယ်။
- Validation with a 400
if (typeof text !== "string" || text.trim().length <= 3) {"hi" က စာလုံး 2 လုံးပဲ ရှိလို့ 400 ဖြစ်ပါတယ်။ trim() ကြောင့် space လေးလုံးလောက်ပဲ ပို့တဲ့ text လည်း ငြင်းခံရပါတယ်။
- 201 with the created resource
return Response.json(quote, { status: 201 });201 Created က "အသစ်ဖန်တီးပြီးပြီ" လို့ ဆိုလိုပါတယ်။ { ok: true } အစား သိမ်းလိုက်တဲ့ quote ကို ပြန်ပေးတော့ author "Unknown" ဖြစ်သွားတာကို client က သိနိုင်ပါတယ်။
- Calling the handler directly
POST(new Request("http://localhost/api/quotes", { method: "POST", body }));Handler တွေက Web standard function ဖြစ်လို့ server မဖွင့်ဘဲ unit test လုပ်လို့ ရပါတယ်။ NextRequest ရဲ့ အပို feature တွေ သုံးရင်တော့ ဒီလောက် ရိုးရှင်းမှာ မဟုတ်ပါဘူး။
201 {"text":"Simple is better than complex.","author":"Unknown"}
400 {"error":"text must be longer than 3 characters"}
400 {"error":"Body must be JSON"}
200 2 quotesTask 3: subscribe form နဲ့ useActionState
Action logic ကို challenge မှာ ရေးပါမယ်။ ဒီမှာ form ဘက်ကို ကြည့်ပါ။ Form က Client Component ဖြစ်ရပါတယ်၊ useActionState က hook ဖြစ်လို့ပါ။ state.status ကို ကြည့်ပြီး error ဒါမှမဟုတ် success စာကို ပြပါတယ်။ role="alert" နဲ့ aria-live က screen reader တွေကို စာပြောင်းသွားကြောင်း အသိပေးပါတယ်။
"use client";
import { useActionState } from "react";
import { subscribe } from "@/app/actions"; // "use server" file
export function SubscribeForm() {
const [state, formAction, pending] = useActionState(subscribe, { status: "idle" });
return (
<form action={formAction}>
<label htmlFor="email">Email</label>
<input id="email" name="email" type="email" />
<button type="submit" disabled={pending}>Subscribe</button>
<p role="alert" aria-live="polite">
{state.status === "idle" ? "" : state.message}
</p>
</form>
);
}Task 4: cache tag ကပ်ပြီး invalidate လုပ်မယ်
// lib/quotes.ts - needs cacheComponents: true (see the caching lesson)
import { cacheTag } from "next/cache";
export async function getQuotes() {
"use cache";
cacheTag("quotes");
return db.quote.findMany();
}
// app/actions.ts - a Server Action: the user should see their change at once
"use server";
import { updateTag } from "next/cache";
export async function addQuote(formData: FormData) {
await db.quote.create({ data: { text: String(formData.get("text")) } });
updateTag("quotes");
}
// app/api/quotes/route.ts - Route Handlers cannot call updateTag
import { revalidateTag } from "next/cache";
// ...after quotes.push(quote) in POST:
revalidateTag("quotes", "max");revalidateTag("quotes", "max") က data ကို "stale" လို့ပဲ မှတ်ပါတယ်။ နောက် visitor က အဟောင်းကို ခဏ မြင်ရပြီး နောက်ကွယ်မှာ အသစ်ယူပါတယ်။ ချက်ချင်း မရှိတော့ရမယ်ဆိုရင် docs အတိုင်း { expire: 0 } ကို ဒုတိယ argument အဖြစ် ပေးပါ။ Argument တစ်ခုတည်းနဲ့ revalidateTag("quotes") ဆိုတဲ့ ပုံစံ အဟောင်းကိုတော့ deprecated လုပ်ထားပါတယ်။ အောက်က model လေးက tag-based cache ရဲ့ အဓိကအချက်ကို ပြပါတယ်။ Tag ကို invalidate မလုပ်မချင်း data အသစ်ကို မမြင်ရပါဘူး။
type Entry = { value: string[]; tags: string[] };
const cache = new Map<string, Entry>();
let dbQuotes = ["Make it work, make it right, make it fast."];
let loads = 0;
function cached(key: string, tags: string[], load: () => string[]): string[] {
const hit = cache.get(key);
if (hit) return hit.value;
loads++;
const value = load();
cache.set(key, { value, tags });
return value;
}
function invalidateTag(tag: string): void {
for (const [key, entry] of cache) if (entry.tags.includes(tag)) cache.delete(key);
}
const getQuotes = () => cached("quotes:list", ["quotes"], () => [...dbQuotes]);
console.log(getQuotes().length, "loads:", loads);
dbQuotes = [...dbQuotes, "Simple is better than complex."];
console.log(getQuotes().length, "loads:", loads, "(stale: tag not invalidated)");
invalidateTag("quotes");
console.log(getQuotes().length, "loads:", loads, "(fresh after invalidation)");လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Route Handler တွေကို mobile app၊ ပြင်ပ partner တွေ ဒါမှမဟုတ် Stripe လို service ရဲ့ webhook တွေက ခေါ်လေ့ရှိပါတယ်။ အဲဒီ client တွေက status code ကို ကြည့်ပြီး retry လုပ်မလား၊ error ပြမလား ဆုံးဖြတ်လို့ status မှန်ဖို့ အရမ်းအရေးကြီးပါတယ်။ ကိုယ့် app ရဲ့ form တွေအတွက်တော့ API route ထက် Server Action ကို ပိုသုံးကြပါတယ်။ Server Component ကလည်း data လိုရင် ကိုယ့် Route Handler ကို fetch ပြန်လုပ်စရာ မလိုဘဲ data function ကို တိုက်ရိုက် ခေါ်လို့ ရပါတယ်။
CMS ကို သုံးတဲ့ blog တွေမှာ editor က post ကို publish လုပ်လိုက်တာနဲ့ CMS က webhook နဲ့ Route Handler ကို ခေါ်ပြီး revalidateTag နဲ့ ဆိုင်ရာ page တွေကို refresh လုပ်ပါတယ်။ ဒါကြောင့် site တစ်ခုလုံး ပြန် build မလုပ်ဘဲ မိနစ်ပိုင်းအတွင်း content အသစ် ပေါ်လာပြီး စာဖတ်သူတွေကလည်း page ပြန်ထုတ်လိုက်တာကို သတိတောင် မထားမိပါဘူး။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
request.json() ကို await မလုပ်တာ
const body = request.json() လို့ ရေးရင် body က Promise ဖြစ်ပြီး body.text က အမြဲ undefined ပါ။ Validation က အမြဲ fail ဖြစ်ပြီး request တိုင်း 400 ရပါတယ်။ TypeScript က any ဖြစ်နေလို့ မသတိပေးတတ်ပါဘူး။
Error ကို 200 နဲ့ ပြန်ပေးတာ
Response.json({ error }) လို့ status မပါရင် default က 200 ပါ။ fetch ရဲ့ response.ok က true ဖြစ်လို့ client က error ကို လွတ်သွားပါတယ်။ Error တိုင်းမှာ { status: 400 } လို status ကို ထည့်ပါ။
Tag ကပ်ထားရင် cache ဖြစ်ပြီလို့ ထင်တာ
Tag က cache လုပ်ထားတဲ့ data ကိုသာ ဖြုတ်ဖို့ လမ်းညွှန်ပါ။ fetch မှာ caching က opt-in ဖြစ်လို့ cache: "force-cache" (ဒါမှမဟုတ် "use cache") မပါရင် invalidate လုပ်စရာ entry ပဲ မရှိနိုင်ပါဘူး။ ပြောင်းပြန်အနေနဲ့ tag ကပ်ပြီး invalidate လုပ်ဖို့ မေ့ရင်တော့ data အဟောင်း ဆက်ပေါ်နေပါတယ်။
Route Handler ထဲမှာ updateTag ခေါ်တာ
updateTag ကို Server Action ထဲမှာပဲ ခေါ်ခွင့်ရှိပြီး Route Handler ထဲမှာ ခေါ်ရင် error throw လုပ်ပါတယ်။ အဲဒီနေရာမှာ revalidateTag(tag, "max") ကို သုံးပါ။
Best Practices
လေ့ကျင့်ရင်း ထားရမယ့် အလေ့အထ
- Endpoint တစ်ခုစီအတွက် curl command တွေကို text file တစ်ခုထဲ သိမ်းထားပြီး code ပြင်တိုင်း ပြန် run ပါ
- Validation logic ကို route.ts ဒါမှမဟုတ် actions.ts ထဲမှာ မရေးဘဲ lib/ ထဲက pure function အဖြစ် ခွဲထုတ်ပါ။ Framework မပါဘဲ test လုပ်လို့ ရပါတယ်
- Mutation တစ်ခု ရေးပြီးတိုင်း "ဒီ data ကို ဘယ် page က ပြလဲ၊ ဘယ် tag ကို ရှင်းရမလဲ" ဆိုတာ ကိုယ့်ကိုယ်ကို မေးပါ
Mini challenge
subscribe action ရဲ့ logic ကို ရေးပါ
Task 3 ရဲ့ subscribe Server Action ကို useActionState နဲ့ သုံးလို့ရတဲ့ (prevState, formData) => state ပုံစံနဲ့ ရေးပါ။ Email ကို သန့်ရှင်းအောင်လုပ်၊ format စစ်၊ ထပ်နေတာ ငြင်းပြီး state သုံးမျိုး (idle၊ error၊ success) ကို ပြန်ပေးပါ။ Database အစား Set တစ်ခု သုံးပါ။
- SubscribeState ကို status ပေါ်မူတည်တဲ့ discriminated union အဖြစ် ရေးပါ
- Email ကို trim + lowercase လုပ်ပြီးမှ regex နဲ့ စစ်ပါ
- Error state မှာ user ရိုက်ခဲ့တဲ့ email ကို ပြန်ထည့်ပါ
- useActionState လိုပဲ state ကို call တစ်ခုကနေ နောက်တစ်ခုဆီ ပေးပြီး input သုံးခုကို စမ်းပါ
type SubscribeState =
| { status: "idle" }
| { status: "error"; message: string; email: string }
| { status: "success"; message: string };
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const subscribers = new Set<string>();
async function subscribe(
_prev: SubscribeState,
formData: FormData,
): Promise<SubscribeState> {
// TODO: read "email", trim it, lowercase it
// TODO: invalid format -> error state; already in the Set -> error state
// TODO: otherwise add it and return a success state
}
// TODO: loop over three inputs, passing the previous state each timeရလဒ်: "not-an-email" က error state၊ " Ko.Aung@Example.com " က "Subscribed ko.aung@example.com" success state၊ "ko.aung@example.com" က already subscribed error ဖြစ်ပြီး နောက်ဆုံးမှာ subscribers: 1 ပေါ်ပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
String(formData.get("email") ?? "") က null ကို ကာကွယ်ပါတယ်။ Lowercase ပြောင်းထားမှ "Ko.Aung@Example.com" နဲ့ "ko.aung@example.com" ကို email တူတူလို့ သိပါမယ်။
အဖြေ ကြည့်ရန်
type SubscribeState =
| { status: "idle" }
| { status: "error"; message: string; email: string }
| { status: "success"; message: string };
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const subscribers = new Set<string>(); // stands in for a database table
async function subscribe(
_prev: SubscribeState,
formData: FormData,
): Promise<SubscribeState> {
const email = String(formData.get("email") ?? "").trim().toLowerCase();
if (!EMAIL.test(email)) {
return { status: "error", message: "Enter a valid email address", email };
}
if (subscribers.has(email)) {
return { status: "error", message: "That email is already subscribed", email };
}
subscribers.add(email);
return { status: "success", message: `Subscribed ${email}` };
}
// Simulate what useActionState does: feed each result into the next call.
async function main() {
let state: SubscribeState = { status: "idle" };
for (const input of ["not-an-email", " Ko.Aung@Example.com ", "ko.aung@example.com"]) {
const form = new FormData();
form.set("email", input);
state = await subscribe(state, form);
console.log(JSON.stringify(input), "->", JSON.stringify(state));
}
console.log("subscribers:", subscribers.size);
}
main();Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Route Handler က Request → Response function ဖြစ်လို့ new Request() နဲ့ တိုက်ရိုက် test လုပ်လို့ ရပါတယ်
- Invalid JSON နဲ့ validation error ကို 400၊ အသစ်ဖန်တီးတာကို 201 နဲ့ ပြန်ပေးပါ
- useActionState နဲ့ action က (prevState, formData) ကို ရပြီး state အသစ်ကို return ပြန်ပါတယ်
- Tag ကို cache လုပ်ထားတဲ့ data မှာ ကပ်ပြီး Server Action မှာ updateTag၊ Route Handler မှာ revalidateTag(tag, "max") နဲ့ ဖြုတ်ပါ
Next.js Documentation — Next.js