ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
ဒီ practice မှာ စာအုပ်ဆိုင်လေးတစ်ခုရဲ့ API ကို ဆောက်ပါမယ်။ စာအုပ်စာရင်း ကြည့်တာ၊ စာအုပ်တစ်အုပ် ရှာတာ၊ စာအုပ်အသစ် ထည့်တာကို အရင်ရေးပြီး mini challenge မှာ ပြင်တာနဲ့ ဖျက်တာကို ထပ်ထည့်ပါမယ်။
အသစ်ပါလာတာက "စောင့်ရတာ" ပါ။ တကယ့် database ကို မေးတဲ့အခါ အဖြေက ချက်ချင်း မရောက်ဘဲ millisecond အနည်းငယ် ကြာပါတယ်။ ဒီ lesson မှာ array ကို database အတုအဖြစ် သုံးပြီး method တိုင်းကို async လုပ်ကာ delay() နဲ့ စောင့်ခိုင်းထားပါတယ်။ ဒါမှ နောက်ပိုင်း database အစစ် ချိတ်တဲ့အခါ route code ကို ပြင်စရာ မလိုတော့ပါဘူး။
Problem → Why → Solution
ပြဿနာ: await မေ့တာနဲ့ Express 4 ခေတ်က အကြံ
အောက်က handler မှာ await မပါလို့ book က object မဟုတ်ဘဲ Promise ဖြစ်နေပါတယ်။ Promise က အမြဲ truthy ဖြစ်လို့ 404 စစ်ချက်ကို ကျော်သွားပြီး res.json(book) က {} ကို ပြန်ပို့ပါတယ်။ Error တစ်ခုမှ မတက်ဘဲ data မှားပဲ ထွက်လာပါတယ်။
နောက်ထပ် အယူအဆတစ်ခုက "async handler ထဲမှာ try/catch မထည့်ရင် server crash ဖြစ်မယ်" ဆိုတာပါ။ ဒါက Express 4 မှာ မှန်ပါတယ်၊ reject ဖြစ်တဲ့ promise ကို Express 4 က မဖမ်းပေးလို့ request က response မရဘဲ ချိတ်မိနေတတ်ပါတယ်။ Express 5 မှာတော့ ပြောင်းသွားပါပြီ။
app.get('/books/:id', async (req, res) => {
const book = bookStore.findById(Number(req.params.id)); // missing await
if (!book) { // a Promise is truthy
return res.status(404).json({ error: 'Book not found' });
}
res.json(book); // sends {}
});ဘာကြောင့် ဒီလိုဖြစ်တာလဲ
Async function တိုင်းက ချက်ချင်း Promise တစ်ခု ပြန်ပေးပြီး တကယ့် value က နောက်မှ ရောက်ပါတယ်။ await က "value ရောက်တဲ့အထိ ဒီ function ကို ခဏရပ်ထား" လို့ ပြောတာပါ။ JSON.stringify က Promise object ကို field မရှိတဲ့ object အဖြစ် မြင်လို့ {} ထွက်ပါတယ်။
Core concept: async route တွေ ဘယ်လို အလုပ်လုပ်လဲ
Original task လေးခုကို အဆင့်လိုက် ပြန်ကြည့်ရင် route တိုင်းမှာ "data store ကို await နဲ့ မေး၊ ရလဒ်ပေါ် မူတည်ပြီး status ရွေး" ဆိုတဲ့ ပုံစံတစ်ခုတည်း ရှိပါတယ်။
Task 1-3: route တွေနဲ့ status တွေ
GET /books က { count, data } နဲ့ 200၊ GET /books/:id က တွေ့ရင် 200 မတွေ့ရင် 404၊ POST /books က express.json() နဲ့ body ဖတ်ပြီး title နဲ့ author စစ်ကာ 201 ဒါမှမဟုတ် 400 ပြန်ပါတယ်။ id ကို books.length + 1 မဟုတ်ဘဲ nextId counter နဲ့ ပေးပါတယ်၊ delete လုပ်ပြီးနောက် id ထပ်မနေအောင်ပါ။
Task 4: delay() helper
setTimeout က callback ပုံစံ ဖြစ်လို့ await နဲ့ တိုက်ရိုက် မသုံးနိုင်ပါဘူး။ new Promise((resolve) => setTimeout(resolve, ms)) က ms ကြာမှ resolve ဖြစ်တဲ့ Promise ကို ဖန်တီးပေးလို့ await delay(100) လို့ ရေးနိုင်ပါတယ်။ စောင့်နေစဉ်မှာ event loop က တခြား request တွေကို ဆက်ဖြေနေလို့ server တစ်ခုလုံး မရပ်ပါဘူး။
Express 5 က async error တွေကို ဖမ်းပေးတယ်
Express 5 မှာ route handler က Promise ပြန်ပြီး အဲဒီ Promise က reject ဖြစ်ရင် Express က error ကို next(err) လို error handler ဆီ အလိုလို ပို့ပေးပါတယ်။ ဒါကြောင့် route တိုင်းမှာ try/catch ထည့်စရာ မလိုတော့ဘဲ app အဆုံးမှာ error handler တစ်ခုပဲ လိုပါတယ်။ Error တစ်ခုကို နေရာမှာတင် ကိုင်တွယ်ချင်တဲ့အခါ (ဥပမာ fallback value ပြန်ချင်ရင်) မှသာ try/catch ကို သုံးပါ။
| Express 4 | Express 5 | |
|---|---|---|
| Async handler reject ဖြစ်ရင် | Error handler ဆီ မရောက်၊ request ချိတ်နိုင် | Error handler ဆီ အလိုလို ရောက် |
| လိုအပ်တဲ့ code | try/catch + next(err) ဒါမှမဟုတ် wrapper | ဘာမှ မလို |
filter() နဲ့ ဖျက်ရင် ဘယ်သူက reassign လုပ်ခွင့်ရှိလဲ
DELETE ကို array.filter() နဲ့ ရေးတာ အသုံးများပါတယ်။ filter() က array အသစ် ပြန်ပေးလို့ ရလဒ်ကို တစ်နေရာမှာ ပြန်သိမ်းရပါတယ်။ Mini challenge မှာ ဒီ reassign ကို store ရဲ့ remove() ထဲမှာပဲ လုပ်ပါတယ်။ Array ကို store တစ်ခုတည်းက ပိုင်တာမို့ လုံခြုံပါတယ်။ Route handler တွေ ကိုယ်တိုင် shared array ကို reassign လုပ်တာကတော့ GET list lesson မှာ တွေ့ခဲ့တဲ့ bug အမျိုးအစားပါ။
- Route က async store method ကို ခေါ်
- await က value ရောက်တဲ့အထိ စောင့်
- Value ပေါ်မူတည်ပြီး 2xx/4xx ရွေး
- Reject ဖြစ်ရင် error handler က 500
Store method ကို ခေါ်တိုင်း await ပါလား စစ်ပါ။ await မပါရင် value မဟုတ်ဘဲ Promise ကို ကိုင်ထားရပါတယ်။
အခြေခံ ပုံစံ
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const store = { async findById(id) { await delay(ms); return found ?? null; } };
app.get('/things/:id', async (req, res) => {
const thing = await store.findById(Number(req.params.id));
if (!thing) return res.status(404).json({ error: 'not found' });
res.json({ data: thing });
});
app.use((err, req, res, next) => res.status(500).json({ error: 'message' }));Store method တွေက async ဖြစ်ပြီး route တွေက await နဲ့ ခေါ်ပါတယ်။ ပျက်တဲ့ Promise မှန်သမျှကို အောက်ဆုံးက error handler တစ်ခုတည်းက ဖမ်းပါတယ်။
Books API: task လေးခုနဲ့ async error တစ်ခု
bookStore object က database အတုပါ။ findById က 100 ms စောင့်လို့ Task 4 ရဲ့ "database ရှာနေတယ်" ဆိုတာကို အတုလုပ်ပါတယ်။ /books/:id/reviews route က အမြဲ fail ဖြစ်တဲ့ review service ကို ခေါ်ပြီး Express 5 က error ကို ဘယ်လို လွှဲပေးလဲ ပြပါတယ်။ အချိန်က စက်အလိုက် နည်းနည်း ကွာလို့ output မှာ millisecond အတိအကျ မပြဘဲ 100 ms လောက် စောင့်ခဲ့လား ဆိုတာကိုပဲ ပြပါတယ်။
const express = require('express');
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// A pretend database: every method is async, just like a real driver
const bookStore = {
books: [
{ id: 1, title: 'Node.js Basics', author: 'Aung' },
{ id: 2, title: 'Express Guide', author: 'Su' },
],
nextId: 3,
async findAll() {
await delay(20);
return this.books;
},
async findById(id) {
await delay(100); // Task 4: simulate a slow lookup
return this.books.find((b) => b.id === id) ?? null;
},
async create(fields) {
await delay(20);
const book = { id: this.nextId++, ...fields };
this.books.push(book);
return book;
},
};
async function fetchReviews() {
await delay(10);
throw new Error('Review service is down');
}
const app = express();
app.use(express.json());
// Task 1: the whole collection
app.get('/books', async (req, res) => {
const books = await bookStore.findAll();
res.json({ count: books.length, data: books });
});
// Task 2 + 4: one book, after an awaited lookup
app.get('/books/:id', async (req, res) => {
const book = await bookStore.findById(Number(req.params.id));
if (!book) return res.status(404).json({ error: 'Book not found' });
res.json({ data: book });
});
// Task 3: create with an auto-increment id
app.post('/books', async (req, res) => {
const { title, author } = req.body ?? {};
const ok = (v) => typeof v === 'string' && v.trim() !== '';
if (!ok(title) || !ok(author)) {
return res.status(400).json({ error: 'title and author are required' });
}
const book = await bookStore.create({ title: title.trim(), author: author.trim() });
res.status(201).json({ data: book });
});
// A failing dependency: Express 5 sends the rejection to the error handler
app.get('/books/:id/reviews', async (req, res) => {
res.json({ data: await fetchReviews() });
});
app.use((err, req, res, next) => {
console.log(' [error handler]', err.message);
res.status(500).json({ error: 'Something went wrong' });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
async function call(method, path, body) {
const init = { method, headers: { 'Content-Type': 'application/json' } };
if (body) init.body = JSON.stringify(body);
const started = performance.now();
const res = await fetch(base + path, init);
const ms = performance.now() - started;
console.log(`${method} ${path} -> ${res.status}`, JSON.stringify(await res.json()));
return ms;
}
await call('GET', '/books');
const ms = await call('GET', '/books/2');
console.log(' waited about 100 ms:', ms >= 90);
await call('GET', '/books/9');
await call('POST', '/books', { title: 'Async Patterns', author: 'Hla' });
await call('POST', '/books', { title: 'No author' });
await call('GET', '/books/1/reviews');
server.close();
});Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Promise-based delay
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));Timer ပြီးတဲ့အခါ resolve ကို ခေါ်လို့ await delay(100) က 100 ms လောက် ကြာမှ ဆက်သွားပါတယ်။
- Async store method
return this.books.find((b) => b.id === id) ?? null;မတွေ့ရင် undefined အစား null ကို တိကျစွာ ပြန်ပါတယ်။ Database driver အများစုလည်း ဒီလိုပဲ လုပ်ပါတယ်။
- Awaited lookup
const book = await bookStore.findById(Number(req.params.id));await ကြောင့် book က Promise မဟုတ်ဘဲ book object ဒါမှမဟုတ် null ဖြစ်ပါတယ်။ ဒါမှ 404 စစ်ချက် အလုပ်လုပ်ပါတယ်။
- Small validator
const ok = (v) => typeof v === 'string' && v.trim() !== '';title နဲ့ author နှစ်ခုလုံးကို စစ်ချက်တစ်ခုတည်းနဲ့ စစ်ပါတယ်။ { title: 'No author' } က author မပါလို့ 400 ရပါတယ်။
- No try/catch needed
res.json({ data: await fetchReviews() });fetchReviews() reject ဖြစ်တဲ့အခါ Express 5 က error handler ကို ခေါ်ပါတယ်။ Output မှာ [error handler] line က client ရဲ့ 500 line မတိုင်ခင် ပေါ်ပါတယ်။
GET /books -> 200 {"count":2,"data":[{"id":1,"title":"Node.js Basics","author":"Aung"},{"id":2,"title":"Express Guide","author":"Su"}]}
GET /books/2 -> 200 {"data":{"id":2,"title":"Express Guide","author":"Su"}}
waited about 100 ms: true
GET /books/9 -> 404 {"error":"Book not found"}
POST /books -> 201 {"data":{"id":3,"title":"Async Patterns","author":"Hla"}}
POST /books -> 400 {"error":"title and author are required"}
[error handler] Review service is down
GET /books/1/reviews -> 500 {"error":"Something went wrong"}စောင့်တာ နှစ်ခုကို တစ်ပြိုင်နက် လုပ်ခြင်း
Route တစ်ခုက စာအုပ်နဲ့ author profile ကို နှစ်ခုလုံး လိုတယ်ဆိုပါစို့။ await နှစ်ခုကို အစဉ်လိုက် ရေးရင် 100 ms + 100 ms = 200 ms လောက် ကြာပါတယ်။ တစ်ခုနဲ့တစ်ခု မမှီခိုရင် Promise.all([findBook(), findAuthor()]) နဲ့ တစ်ပြိုင်နက် စတင်ပြီး နှစ်ခုလုံးကို တစ်ခါတည်း await လုပ်လို့ရပါတယ်။ ဒါဆိုရင် 100 ms လောက်ပဲ ကြာပါတော့တယ်။
Promise.all က တစ်ခုခု reject ဖြစ်တာနဲ့ ချက်ချင်း reject ဖြစ်ပြီး Express 5 က အဲဒါကိုလည်း error handler ဆီ ပို့ပေးပါတယ်။ တစ်ခု fail ရင်တောင် ကျန်တာကို ဆက်ပြချင်ရင်တော့ Promise.allSettled ကို သုံးပါ။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
ဒီ bookStore object လိုမျိုး data access ကို route တွေနဲ့ ခွဲထားတဲ့ layer ကို repository ဒါမှမဟုတ် service layer လို့ ခေါ်ကြပါတယ်။ Database ကို PostgreSQL ကနေ MongoDB ပြောင်းတဲ့အခါ၊ test တွေမှာ database အစစ်အစား memory store ထည့်ချင်တဲ့အခါ ဒီ layer ကိုပဲ ပြောင်းရပြီး route တွေက မပြောင်းပါဘူး။
Production မှာ error handler က တကယ့် error ကို logging system (ဥပမာ structured JSON log) ထဲ request id နဲ့အတူ ရေးပြီး client ကိုတော့ ယေဘုယျ message ပဲ ပြန်ပါတယ်။ Review service လို ပြင်ပ dependency တွေ fail ဖြစ်တာက ပုံမှန်ပါပဲ၊ timeout ထားတာ၊ retry လုပ်တာ၊ fail ရင် reviews မပါဘဲ စာအုပ်ကိုပဲ ပြတာမျိုး ဆုံးဖြတ်ရပါတယ်။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
Store method ကို await မပါဘဲ ခေါ်တာ
Promise က truthy ဖြစ်လို့ if (!book) စစ်ချက် အမြဲ ကျော်ပြီး client က {} ကို 200 နဲ့ ရပါတယ်။ TypeScript နဲ့ typescript-eslint ရဲ့ no-misused-promises rule ကို တွဲသုံးရင် ဒီလို condition ထဲမှာ Promise သုံးမိတာကို သတိပေးနိုင်ပါတယ်။
delay() ကို setTimeout နဲ့ တိုက်ရိုက် await လုပ်တာ
await setTimeout(fn, 500) က timer object ကို ချက်ချင်း ပြန်ပေးလို့ ဘာမှ မစောင့်ပါဘူး။ Promise နဲ့ ထုပ်ထားတဲ့ delay() ကို သုံးပါ၊ ဒါမှမဟုတ် require('node:timers/promises') ရဲ့ setTimeout ကို သုံးပါ။
Express 4 tutorial ရဲ့ wrapper ကို Express 5 မှာ ဆက်ထည့်တာ
asyncHandler(fn) လို wrapper ဒါမှမဟုတ် route တိုင်းမှာ try { } catch (e) { next(e) } ထည့်တာက Express 5 မှာ မလိုတော့ပါဘူး။ Code ပိုရှည်ပြီး error တစ်ခုကို နေရာနှစ်ခုမှာ ကိုင်တွယ်မိတတ်ပါတယ်။
Best Practices
ကောင်းမွန်တဲ့ အလေ့အကျင့်များ
- Route handler တွေက data ကို store method တွေကနေပဲ ထိပါစေ၊ array ကို တိုက်ရိုက် မပြင်ပါနဲ့
- Store method တွေကို အစကတည်းက async ရေးထားပါ၊ database ချိတ်တဲ့အခါ signature မပြောင်းရတော့ပါဘူး
- App တစ်ခုမှာ error handler တစ်ခုတည်း ထားပြီး log ရေးတာနဲ့ 500 ပြန်တာကို အဲဒီမှာပဲ လုပ်ပါ
- Practice script တွေမှာ delay ကို တိုတိုထားပါ (100 ms လောက်)၊ test တွေ မြန်မြန် ပြီးပါမယ်
Mini challenge
PATCH နဲ့ DELETE ထည့်ပြီး CRUD ကို ပြီးအောင်လုပ်ပါ
Async store မှာ update(id, changes) နဲ့ remove(id) method နှစ်ခု ထည့်ပြီး PATCH /books/:id နဲ့ DELETE /books/:id route တွေ ရေးပါ။ PATCH က ပို့လာတဲ့ field (title၊ author) ကိုပဲ ပြင်ပြီး DELETE က array.filter() နဲ့ ဖယ်ကာ 204 ပြန်ပါ။
- PATCH က ပို့လာတဲ့ field တိုင်းကို string အလွတ် မဟုတ်ရဘူးလို့ စစ်ပြီး မှားရင် 400 ပြန်ပါ
- Book မရှိရင် PATCH နဲ့ DELETE နှစ်ခုလုံး 404 ပြန်ပါ
- remove() က တစ်ခုခု ဖယ်လိုက်ရင် true၊ မဟုတ်ရင် false ပြန်ပါ
- DELETE ကို နှစ်ခါ ခေါ်ရင် ပထမ 204၊ ဒုတိယ 404 ဖြစ်ရပါမယ်
const express = require('express');
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const store = {
books: [/* TODO: three books */],
async update(id, changes) {
// TODO: wait, find the book, Object.assign the changes, return it or null
},
async remove(id) {
// TODO: wait, filter the book out, return whether the length shrank
},
};
const app = express();
app.use(express.json());
// TODO: PATCH /books/:id -> 200 { data } | 400 | 404
// TODO: DELETE /books/:id -> 204 | 404
// TODO: listen on 0, send PATCH x2 and DELETE x2, print results, closeရလဒ်: ပထမ PATCH က 200 ("Express 5 Guide")၊ author အလွတ်က 400၊ ပထမ DELETE က 204 (no body)၊ ဒုတိယက 404 ဖြစ်ပြီး left: Express 5 Guide | Async Patterns ကို ပြပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
PATCH မှာ for (const field of ['title', 'author']) နဲ့ loop ပတ်ပြီး req.body?.[field] က undefined ဆိုရင် continue လုပ်ပါ။ ဒါမှ ပို့လာတဲ့ field ကိုပဲ စစ်ပါမယ်။
အဖြေ ကြည့်ရန်
const express = require('express');
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const store = {
books: [
{ id: 1, title: 'Node.js Basics', author: 'Aung' },
{ id: 2, title: 'Express Guide', author: 'Su' },
{ id: 3, title: 'Async Patterns', author: 'Hla' },
],
async update(id, changes) {
await delay(20);
const book = this.books.find((b) => b.id === id);
if (!book) return null;
Object.assign(book, changes);
return book;
},
async remove(id) {
await delay(20);
const before = this.books.length;
this.books = this.books.filter((b) => b.id !== id);
return this.books.length < before; // true if something was removed
},
};
const app = express();
app.use(express.json());
app.patch('/books/:id', async (req, res) => {
const changes = {};
for (const field of ['title', 'author']) {
const value = req.body?.[field];
if (value === undefined) continue;
if (typeof value !== 'string' || value.trim() === '') {
return res.status(400).json({ error: `${field} must be a non-empty string` });
}
changes[field] = value.trim();
}
const book = await store.update(Number(req.params.id), changes);
if (!book) return res.status(404).json({ error: 'Book not found' });
res.json({ data: book });
});
app.delete('/books/:id', async (req, res) => {
const removed = await store.remove(Number(req.params.id));
if (!removed) return res.status(404).json({ error: 'Book not found' });
res.status(204).end();
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const send = async (method, path, body) => {
const res = await fetch(base + path, {
method,
headers: { 'Content-Type': 'application/json' },
body: body && JSON.stringify(body),
});
console.log(method, path, res.status, (await res.text()) || '(no body)');
};
await send('PATCH', '/books/2', { title: 'Express 5 Guide' });
await send('PATCH', '/books/2', { author: '' });
await send('DELETE', '/books/1');
await send('DELETE', '/books/1');
console.log('left:', store.books.map((b) => b.title).join(' | '));
server.close();
});Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Data store method တွေကို async ထားပြီး route တွေက await နဲ့ ခေါ်ရင် database အစစ်ကို နောက်မှ ပြောင်းထည့်ရ လွယ်ပါတယ်
- delay() က setTimeout ကို Promise နဲ့ ထုပ်ထားတာဖြစ်ပြီး စောင့်နေစဉ် တခြား request တွေကို မပိတ်ဆို့ပါဘူး
- Express 5 က async handler ရဲ့ rejection ကို error handler ဆီ အလိုလို ပို့လို့ route တိုင်းမှာ try/catch မလိုပါဘူး
- PATCH က ပို့လာတဲ့ field ကိုပဲ စစ်ပြီး ပြင်ကာ DELETE က 204 (မရှိရင် 404) ပြန်ပါတယ်
Express 5 error handling — Express.js