router.post("/signup", userController.signup); router.get("/profile", authMiddleware, userController.getProfile); CODE_BLOCK: router.post("/signup", userController.signup); router.get("/profile", authMiddleware, userController.getProfile); CODE_BLOCK: router.post("/signup", userController.signup); router.get("/profile", authMiddleware, userController.getProfile); CODE_BLOCK: router.get("/profile", authMiddleware, userController.getProfile); CODE_BLOCK: router.get("/profile", authMiddleware, userController.getProfile); CODE_BLOCK: router.get("/profile", authMiddleware, userController.getProfile); COMMAND_BLOCK: exports.signup = async ({ email, password }) => { const existingUser = await userRepository.findByEmail(email); if (existingUser) { throw new Error("User already exists"); } const hashedPassword = await bcrypt.hash(password, 10); return await userRepository.createUser(email, hashedPassword); }; COMMAND_BLOCK: exports.signup = async ({ email, password }) => { const existingUser = await userRepository.findByEmail(email); if (existingUser) { throw new Error("User already exists"); } const hashedPassword = await bcrypt.hash(password, 10); return await userRepository.createUser(email, hashedPassword); }; COMMAND_BLOCK: exports.signup = async ({ email, password }) => { const existingUser = await userRepository.findByEmail(email); if (existingUser) { throw new Error("User already exists"); } const hashedPassword = await bcrypt.hash(password, 10); return await userRepository.createUser(email, hashedPassword); }; COMMAND_BLOCK: exports.findByEmail = async (email) => { return db("users").where({ email }).first(); }; COMMAND_BLOCK: exports.findByEmail = async (email) => { return db("users").where({ email }).first(); }; COMMAND_BLOCK: exports.findByEmail = async (email) => { return db("users").where({ email }).first(); };
- Controllers
- Reading request data (req.body, req.params, req.query)
- Sending response (res.json, res.status)
- Calling the service layer
- Contain business logic
- Talk directly to the database
- Hash passwords
- Calculate business rules
- Authentication (JWT verification)
- Input validation
- Rate limiting
- Error handling
- Business rules
- Data transformations
- Workflow decisions
- Communicating with the database
- Executing queries
- Returning raw data
- Decide business rules
- Validate logic
- Handle HTTP
- Retrieve data
- Maintain integrity
- Business logic
- Application rules
- It only stores information
- Let’s say a user signs up.
- Request hits Route
- Middleware validates token/input
- Controller receives request
- Controller calls Service
- Service applies business logic
- Service calls Repository
- Repository talks to Database
- Response travels back up the chain