ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
ဒီ Practice Set 1 ထက် တစ်ဆင့်ခက်ပြီး data layer နဲ့ mutation logic ကို အာရုံစိုက်ပါတယ်။ Task တစ်ခုစီက production app တွေမှာ တွေ့ရမယ့် pattern အစစ်တွေဖြစ်တဲ့ API endpoint ရေးခြင်း၊ form validation, cache invalidation တို့ကို ဖုံးအုပ်ထားပါတယ်။ ဒီ task တွေကို ပြီးအောင်လုပ်ရင်း error handling ကိုလည်း တစ်ပါတည်း ဂရုစိုက်ကြည့်ပါ.
လေ့ကျင့်ခန်းများ
(1) app/api/quotes/route.ts route handler တစ်ခုဖန်တီးပြီး GET method ထဲမှာ quote array (text, author) ကို JSON အနေနဲ့ Response.json() ပြန်ပေးပါ။ (2) POST method ထပ်ထည့်ပြီး request body ရဲ့ text field ကို string ဟုတ်မဟုတ်နဲ့ length 3 ထက်ကြီးမကြီး validate လုပ်ပါ — မမှန်ရင် status 400 ပြန်ပါ။ (3) "use server" Server Action တစ်ခုနဲ့ subscribe form (email input) တစ်ခု ဖန်တီးပြီး email format ကို regex နဲ့ validate လုပ်ပြီး success/error message ကို useFormState သို့မဟုတ် simple state နဲ့ ပြပါ။ (4) data ပြောင်းလဲမှုတစ်ခုနောက်မှာ revalidateTag("quotes") ကိုသုံးပြီး fetch() call တစ်ခုမှာ { next: { tags: ["quotes"] } } option ကို ချိတ်ဆက်ကြည့်ပါ.
Code နမူနာ
// Task 1-2 skeleton — app/api/quotes/route.ts
const quotes = [{ text: "Stay hungry, stay foolish.", author: "Steve Jobs" }];
export async function GET() {
return Response.json(quotes);
}
export async function POST(request: Request) {
const body = await request.json();
if (typeof body.text !== "string" || body.text.length <= 3) {
return Response.json({ error: "text is too short" }, { status: 400 });
}
quotes.push({ text: body.text, author: body.author ?? "Unknown" });
return Response.json({ ok: true }, { status: 201 });
}
// Task 3 skeleton — app/actions.ts
"use server";
export async function subscribe(prevState: unknown, formData: FormData) {
const email = String(formData.get("email") ?? "");
const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
if (!isValid) return { error: "Invalid email address" };
return { success: true };
}Task 4 ခုစလုံးပြီးရင် API endpoint validate logic ပါတဲ့ backend, form validation ပါတဲ့ Server Action, tag-based cache invalidation တို့ တွဲလုပ်နိုင်တဲ့ data flow တစ်ခုလုံး ကိုယ်တိုင် ရေးဖွဲ့နိုင်ပါလိမ့်မယ်။၅ မိနစ် စမ်းကြည့်
Task (2) ရဲ့ POST endpoint ကို curl -X POST -d '{"text":"hi"}' လို short text တစ်ခုနဲ့ 5 မိနစ်အတွင်း test လုပ်ပြီး status 400 ပြန်လာကြောင်း confirm လုပ်ပါ။
သတိလေးတစ်ချက်
route handler ထဲမှာ error case အတွက် status code ကို သေချာသတ်မှတ်ပါ — default 200 ပြန်ရင် client-side code က success လို့ထင်ပြီး validation error ကို လွဲချော်တတ်ပါတယ်။