CRUD Routes End-to-End
Ek maintainable Express app mein routes sirf HTTP concerns handle karte hain (params padhna, status code, response shape) aur business logic service layer mein rehta hai. Isse logic test karna aasaan ho jaata hai — bina HTTP server chalaaye.
Har CRUD operation ka apna sahi status code hota hai: create par 201 (Location header ke saath), successful delete par 204 (no body), aur update par 200 ya 204. Missing resource par 404, galat input par 400.
// routes/users.js
router.post("/", asyncH(async (req, res) => {
const user = await userService.create(req.body); // logic service mein
res.status(201).location(`/users/${user.id}`).json(user);
}));
router.delete("/:id", asyncH(async (req, res) => {
await userService.remove(req.params.id);
res.status(204).end();
}));- Routes = HTTP layer, services = business logic, models = data access
- Create par 201 + Location header, delete par 204 without body
- Logic service mein hone se unit testing bina HTTP ke ho jaati hai
Route file sirf HTTP samajhti hai, service file business rules, aur model/repository data access. Isse ek hi service logic REST route, GraphQL resolver aur background job — teenon jagah reuse ho sakti hai, aur unit tests bina HTTP ke chalte hain.
// routes/users.js -> HTTP
router.get("/:id", asyncH(async (req, res) => {
res.json(await userService.getById(req.params.id));
}));
// services/userService.js -> logic
exports.getById = async (id) => {
const u = await userRepo.find(id);
if (!u) throw new AppError("User not found", 404);
return u;
};PUT poora resource REPLACE karta hai — jo fields nahi bheje, wo hat jaate hain (idempotent). PATCH sirf bheje gaye fields update karta hai. Client ko clear API documentation deni chahiye, warna PUT se accidentally data khali ho jaata hai.
router.put("/:id", replaceUser); // poora object chahiye
router.patch("/:id", updateFields); // sirf badle hue fields