Loading Depth Study
Preparing your workspace
A layered backend keeps routing, request handling, business rules, and data access separated so each part has a clear responsibility.
Small applications can start with route handlers, but larger projects become difficult to maintain when every route contains validation, business logic, and database queries. A controller can handle HTTP-specific responsibilities such as reading parameters and sending responses. A service can contain business rules, while a repository or data-access layer can handle database operations. This separation makes code easier to test, reuse, and change.
A course creation request can pass from a route to a controller, then to a course service, and finally to a database repository.
async function createCourseService(input) {
if (!input.title) {
throw new Error('Course title is required');
}
return courseRepository.create(input);
}
async function createCourseController(req, res, next) {
try {
const course = await createCourseService(req.body);
res.status(201).json(course);
} catch (error) {
next(error);
}
}The controller handles HTTP input and output while the service handles business rules and delegates data storage.