🧮
REST APIs with Express

CRUD Routes End-to-End

Controller, Service, Route Layers
💡 CRUD app ko layers mein baantna EK RESTAURANT jaisa hai — waiter (route) order leta hai, kitchen (service) khana banata hai, store room (model) saamaan rakhta hai. Waiter ko recipe nahi pata honi chahiye.

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();
}));
🧮
CRUD app ko layers mein baantna EK RESTAURANT jaisa hai — waiter (route) order leta hai, kitchen (service) khana banata hai, store room (model) saamaan rakhta hai. Waiter ko recipe nahi pata honi chahiye.
1 / 2
⚡ झट से Recap
  • 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
इस page में (2 subtopics)

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