Service Layer
ELI5 — The Vibe Check
Service Layer is the middle manager of your app. Controllers receive HTTP requests and hand off to services. Services contain all the actual business logic. Repositories deal with the database. Services are the brain that orchestrates it all without getting their hands dirty.
Real Talk
The Service Layer defines an application's boundary with a set of available operations from the perspective of interfacing client layers. It encapsulates business logic, controls transactions, and coordinates domain objects and repositories. Sits between controllers and repositories.
Show Me The Code
// Controller delegates to service
class UserController {
async createUser(req, res) {
const user = await this.userService.createUser(req.body);
res.json(user);
}
}
// Service contains business logic
class UserService {
async createUser(data: CreateUserDto) {
await this.validator.validate(data);
const user = new User(data);
await this.emailService.sendWelcome(user);
return this.userRepository.save(user);
}
}
When You'll Hear This
"Put that logic in the service layer, not the controller." / "The service layer is the heart of your application's business rules."
Related Terms
Clean Architecture
Clean Architecture is like an onion with strict rules: the inner layers (your core business logic) have absolutely no idea the outer layers (databases, API...
MVC (MVC)
MVC is like a restaurant: the Model is the kitchen (data and logic), the View is the plate of food (what the user sees), and the Controller is the waiter (...
Repository Pattern
Repository Pattern puts a layer between your business logic and your database, so your business code never writes SQL directly.
Separation of Concerns
Separation of Concerns means different parts of your code should handle different concerns and not step on each other's toes.