Lesson 4 of 8
Service vs Controller Architecture
Production Express apps separate **Controllers** (HTTP boundary - parse request, call service, send response) from **Services** (business logic - no knowledge of HTTP). Both layers are fully typed. Controllers own the HTTP types; Services own the domain types. This separation makes business logic testable without HTTP scaffolding and makes HTTP handling reusable across different protocols.
Controller vs Service - Typed Separation of Concerns
// ── Service layer - pure business logic, no HTTP ────────────
// Services accept and return DOMAIN types only.
// No Request, Response, or NextFunction anywhere in services.
interface CreateTaskInput {
title: string;
priority: Priority;
description?: string;
dueDate?: Date;
}
interface TaskQuery {
status?: TaskStatus;
priority?: Priority;
page: number;
perPage: number;
}
interface PaginatedTasks {
items: Task[];
total: number;
page: number;
perPage: number;
}
class TaskService {
constructor(
private readonly taskRepo: ITaskRepository,
private readonly eventBus: EventBus,
private readonly logger: Logger,
) {}
async createTask(input: CreateTaskInput, creatorId: number): Promise<Task> {
if (!input.title.trim()) throw new AppError(400, "Title cannot be empty");
const task = await this.taskRepo.save({
id: Date.now(),
title: input.title.trim(),
description: input.description ?? null,
priority: input.priority,
status: "todo",
assignee: null,
dueDate: input.dueDate ?? null,
tags: [],
createdAt: new Date(),
updatedAt: new Date(),
});
this.eventBus.emit("task:created", { task });
this.logger.info("Task created", { taskId: task.id, by: creatorId });
return task;
}
async listTasks(query: TaskQuery): Promise<PaginatedTasks> {
return this.taskRepo.findPaginated(query);
}
}
// ── Controller layer - HTTP boundary, calls service ───────────
// Controllers own: parsing, validation, HTTP status codes, response shape.
// They know nothing about the database or business rules.
class TaskController {
constructor(private readonly taskService: TaskService) {}
// POST /api/v1/tasks
create = async (
req: Request<{}, Task | ApiError, CreateTaskBody>,
res: Response<Task | ApiError>,
next: NextFunction,
): Promise<void> => {
try {
const { title, priority = "medium", description, dueDate } = req.body;
if (!title || typeof title !== "string") {
res.status(400).json({ error: "title is required and must be a string" });
return;
}
const task = await this.taskService.createTask(
{
title,
priority,
description,
dueDate: dueDate ? new Date(dueDate) : undefined,
},
req.user!.id,
);
res.status(201).json(task);
} catch (error) {
next(error);
}
};
// GET /api/v1/tasks
list = async (
req: Request<{}, PaginatedTasks | ApiError, {}, TaskListQuery>,
res: Response<PaginatedTasks | ApiError>,
next: NextFunction,
): Promise<void> => {
try {
const result = await this.taskService.listTasks({
status: req.query.status,
priority: req.query.priority,
page: parseInt(req.query.page ?? "1", 10),
perPage: parseInt(req.query.limit ?? "20", 10),
});
res.json(result);
} catch (error) {
next(error);
}
};
}
// ── Router wiring ─────────────────────────────────────────────
const taskController = new TaskController(taskService);
const router = Router();
router.post("/", authMiddleware, taskController.create);
router.get("/", taskController.list);Common Mistakes
- Putting database calls in route handlers - route handlers should never call the DB directly. They call a service method. This allows switching the DB layer without touching route code.
- Putting HTTP status codes in services - services should throw domain errors (`AppError(400, 'Title empty')`), not return HTTP-specific shapes. Controllers convert domain errors to HTTP responses.
- Not binding controller methods - if passing `controller.method` as a route handler reference, the `this` context is lost. Use arrow functions (`create = async (req, res) =>`) instead of regular methods to avoid binding issues.
Tip
Tip
Practice Service vs Controller Architecture in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Service vs Controller Architecture
Practice Task
Note
Practice Task - (1) Write a working example of Service vs Controller Architecture from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Service vs Controller Architecture is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- Production Express apps separate **Controllers** (HTTP boundary - parse request, call service, send response) from **Services** (business logic - no knowledge of HTTP).
- Putting database calls in route handlers - route handlers should never call the DB directly. They call a service method. This allows switching the DB layer without touching route code.
- Putting HTTP status codes in services - services should throw domain errors (`AppError(400, 'Title empty')`), not return HTTP-specific shapes. Controllers convert domain errors to HTTP responses.
- Not binding controller methods - if passing `controller.method` as a route handler reference, the `this` context is lost. Use arrow functions (`create = async (req, res) =>`) instead of regular methods to avoid binding issues.
Finished this lesson?