ဒီ mini project မှာ Express.js နဲ့ Simple User API တစ်ခုတည်ဆောက်ပါမယ်။ Users အားလုံးကြည့်မယ်၊ user တစ်ယောက်ရှာမယ်၊ user အသစ်ထည့်မယ်။ Database မပါသေးပေမယ့် REST API ရဲ့အခြေခံ flow ကိုအပြည့်မြင်နိုင်ပါတယ်။
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
let users = [
{ id: 1, name: 'Aung Aung' },
{ id: 2, name: 'Mya Mya' }
];
app.get('/api/users', (req, res) => {
res.json({ count: users.length, data: users });
});
app.get('/api/users/:id', (req, res) => {
const id = Number(req.params.id);
const user = users.find((item) => item.id === id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json({ data: user });
});
app.post('/api/users', (req, res) => {
const name = req.body.name;
if (!name || name.trim() === '') {
return res.status(400).json({ message: 'Name is required' });
}
const newUser = { id: users.length + 1, name: name.trim() };
users.push(newUser);
res.status(201).json({ message: 'User created', data: newUser });
});
app.use((req, res) => {
res.status(404).json({ message: 'Route not found' });
});
app.listen(port, () => {
console.log(`Simple User API running at http://localhost:${port}`);
});ဒီ project code က lesson အားလုံးကိုပေါင်းထားတာပါ။ Server setup, middleware, GET routes, POST route, validation, fallback 404 route အထိပါပါတယ်။ app.use((req,res)=>...) ကိုအောက်ဆုံးထားထားတာက အပေါ်က route တွေမကိုက်တော့မှ 404 ပြန်ပေးစေချင်လို့ပါ။
Run: node app.js Test endpoints: GET http://localhost:3000/api/users GET http://localhost:3000/api/users/1 POST http://localhost:3000/api/usersInfo
Route order ကိုသတိထားပါ။ 404 fallback ကိုအပေါ်တင်ထားရင် အောက်က route တွေဆီမရောက်တော့ပါ။
နောက်တစ်ဆင့်
ဒီ project ကိုနားလည်ပြီးရင် CRUD အပြည့်အတွက် PUT/PATCH နှင့် DELETE routes တွေကို ကိုယ်တိုင်ထပ်ရေးကြည့်ပါ။