Express Middleware
Benefit
- Small Code with single responsibility → พยายามให้โค้ดมีหน้าที่ความรับผิดชอบแค่อย่างเดียว
- Reuseability → สมมุติ เครื่องทอดโรงงานมาม่า เช่น ไม่ได้ทอดแต่เส้น เอาไปทอดมันฝรั่งเลย์ได้ล่วย
- Easier to maintain
- Less bugs
What can express middleware do ?
- Execute any code
- Make changes to the request and the response objects
- End the request-resoinse cycle
- Call the next middleware function in the stack
ปัญหา code มีหลายหน้าที่เกินไป
foodRouter.get('/menunew/:special', (req, res) => {
//logging
console.log('Request parameters');
console.log(req.params);
const now = new Date();
console.log(now.toISOString());
// Cooking
const { menu } = req.params;
const roastedPorkRice = {
rice: 'rice',
};
roastedPorkRice.meat = 'roasted-pork';
roastedPorkRice.sauces = ['moo-dang-sauce'];
// Serve
res.status(200).json(roastedPorkRice);
});
มีทั้ง loggin cooking serve
เวลาเราทำจริงๆ จะแยก logic ไปไว้ข้างนอก เช่น ทำเรื่อง logging อย่างเดียว
const logger = (req, res, next) => {
//logging
console.log('Request parameters');
console.log(req.params);
const now = new Date();
console.log(now.toISOString());
next(); //next คือ ตัวที่บอกว่า ชั้นทำเสร็จแล้วจ้า ไปอันต่อไปได้เลย
};
//เวลาจะใช้ logger
foodRouter.get('/:menu', logger, (req, res) => {} // เพิ่มลงไปใน get ก็ได้ มันรู้เหมือนกัน ไม่ต้องใช้ use
foodRouter.get('/menunew/:special', logger, (req, res) => {}
// foodRouter.use(logger); ใช้แบบนี้ไม่ได้ express หาไม่เจอ
foodRouter.use('/:menu', logger);
express มี middleware
ให้ใช้อยู่ ที่สำคัญคือ json body-parser
npm i body-parser
var bodyParser = require('body-parser')
เวลา user ส่งข้อมูลเป็น json มันจะช่วยแปลงเป็น string ให้
Restful API Structure
Subject — Verb — Object
ประธาน — กิริยา — กรรม
User — Method — Path
พูดง่ายๆคือ ให้มองว่า มี user พยายามทำอะไรสักอย่างด้วย method โดยสิ่งที่จะโดนทำคือ path(?) credit Boomnoob-kung

Verb
Object (Noun)
Method
/menu/chicken-rice/8888
GET
POST
PUT
DELETE


