Lesson 19 split an app into store, controller and routes. That is enough for a small API. As an app grows, a new problem appears: business rules. Rules such as "a task title cannot be empty" or "a finished task cannot be edited" end up inside route handlers, mixed with HTTP details, and then they are hard to test and easy to copy by mistake. The cure is one more layer, and a habit of passing in what a piece of code needs instead of creating it inside.
Four layers, each with one job
- Controller: speaks HTTP. It reads the request, calls the service and turns the result into a status code and JSON. It contains no business rules.
- Service: holds the rules of your application. It knows nothing about requests, responses or the database engine.
- Repository: the only place that talks to the database. It offers methods such as
findByIdandsave. - Errors: the service raises its own kinds of error, for example
NotFoundErrororRuleError, and one small mapper turns them into 404 or 409.
The direction of dependency matters. The controller depends on the service, and the service depends on a repository *interface*, but never the other way round. The service never imports Express and never imports Mongoose. That is why you could change from MongoDB to PostgreSQL by writing a new repository, and why the business rules stay untouched.
// Layers: route -> controller -> service -> repository. Each layer knows only the one below it.
import express from 'express';
// Repository: the ONLY place that knows how data is stored. Swap it for a Mongoose one without touching anything else.
export function memoryTaskRepository() {
const rows = new Map();
let nextId = 1;
return {
async list(ownerId) { return [...rows.values()].filter((t) => t.ownerId === ownerId); },
async find(id) { return rows.get(id) ?? null; },
async insert(data) { const task = { id: nextId++, done: false, ...data }; rows.set(task.id, task); return task; },
async update(id, changes) { Object.assign(rows.get(id), changes); return rows.get(id); },
};
}
// Service: business rules. It gets its dependencies handed in (dependency injection), so tests can pass fakes.
export class TaskService {
constructor({ tasks, clock = () => new Date() }) {
this.tasks = tasks;
this.clock = clock;
}
async create(ownerId, title) {
if (!title?.trim()) throw new ValidationError('title is required');
if ((await this.tasks.list(ownerId)).filter((t) => !t.done).length >= 3) {
throw new RuleError('Finish a task before adding more than 3 open tasks'); // a business rule, not an HTTP rule
}
return this.tasks.insert({ ownerId, title: title.trim(), createdAt: this.clock().toISOString() });
}
async complete(ownerId, id) {
const task = await this.tasks.find(id);
if (!task || task.ownerId !== ownerId) throw new NotFoundError('Task not found'); // do not reveal other people's ids
return this.tasks.update(id, { done: true });
}
}
export class ValidationError extends Error {}
export class RuleError extends Error {}
export class NotFoundError extends Error {}
// Controller: HTTP in, HTTP out. No rules here.
export function taskController(service) {
return {
create: async (req, res) => res.status(201).json(await service.create(req.userId, req.body?.title)),
complete: async (req, res) => res.json(await service.complete(req.userId, Number(req.params.id))),
};
}
// Composition root: the one place where real objects are wired together.
export function createApp({ tasks = memoryTaskRepository() } = {}) {
const app = express();
app.use(express.json());
app.use((req, res, next) => { req.userId = Number(req.get('x-user-id') ?? 1); next(); }); // stand-in for real auth
const controller = taskController(new TaskService({ tasks }));
app.post('/tasks', controller.create);
app.post('/tasks/:id/complete', controller.complete);
// Map business errors to HTTP in ONE place.
app.use((err, req, res, next) => {
if (err instanceof ValidationError) return res.status(422).json({ error: err.message });
if (err instanceof RuleError) return res.status(409).json({ error: err.message });
if (err instanceof NotFoundError) return res.status(404).json({ error: err.message });
res.status(500).json({ error: 'Something went wrong' });
});
return app;
}
Dependency injection without a framework
Look at how TaskService is built: new TaskService(repository). The service does not create its repository. It receives it. This is dependency injection, and in JavaScript it needs no special library, just constructor or function parameters. The place where everything is wired together, here createApp, is called the composition root. In a test you pass a memory repository, and in production you pass the real one.
The first test below does not use HTTP at all: it creates a service with a memory repository and calls its methods directly. It runs in a few milliseconds. The second test goes through HTTP with Supertest and checks that the error mapper gives the right status codes. Both pass.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Install what the lesson needs:
npm install express. - Save the code as
layers.js. The test needsnpm install -D supertest.
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp, TaskService, memoryTaskRepository, RuleError } from './ar33-layers.js';
test('service rules can be tested with no HTTP at all', async () => {
const service = new TaskService({ tasks: memoryTaskRepository(), clock: () => new Date('2026-01-01T00:00:00Z') });
const first = await service.create(1, ' Write notes ');
assert.equal(first.title, 'Write notes');
assert.equal(first.createdAt, '2026-01-01T00:00:00.000Z');
await service.create(1, 'Two');
await service.create(1, 'Three');
await assert.rejects(service.create(1, 'Four'), RuleError);
await service.complete(1, first.id);
await service.create(1, 'Four now fits');
});
test('through HTTP: status codes come from the error mapper', async () => {
const app = createApp();
assert.equal((await request(app).post('/tasks').send({})).status, 422);
const task = await request(app).post('/tasks').send({ title: 'A' });
assert.equal(task.status, 201);
assert.equal((await request(app).post(`/tasks/${task.body.id}/complete`).set('x-user-id', '2')).status, 404); // not your task
assert.equal((await request(app).post(`/tasks/${task.body.id}/complete`)).body.done, true);
});
SOLID, in one paragraph each
SOLID is a set of five design ideas that interviewers like to ask about. You do not need to memorise them as rules. They describe the same habits you just used.
- S, single responsibility: a piece of code has one reason to change. The controller changes when the API shape changes, the service when the rules change, the repository when the database changes.
- O, open/closed: you can add behaviour without editing working code. A new payment provider is a new file, not an edit of the old ones.
- L, Liskov substitution: any repository that follows the same methods can replace another. The memory repository and the MongoDB repository are interchangeable.
- I, interface segregation: keep contracts small. A service that only reads should not need a repository with ten write methods.
- D, dependency inversion: depend on a contract, not on a concrete tool. The service depends on "a repository", not on Mongoose.
Do not over-build
Layers cost files and indirection. For a three-route API they are more than you need, and a pile of empty "manager" classes helps nobody. Add a layer when it solves a problem you have: rules scattered across handlers, tests that need a database, a plan to change the data store. Clean architecture, the name for pushing this idea all the way, is a direction, not a goal. Start simple, and refactor towards layers when the pain appears.
Your task
- Add a
completerule to the service: a completed task cannot be completed again, and make it return 409. - Write a second repository that stores tasks in a JSON file and pass it to the service.
- Write a service test with a fake repository that throws, and see how the error is handled.
How to check it worked
- The service test passes with no HTTP.
- You can explain what the composition root is.
- You can name the layer that you would change when moving from MongoDB to PostgreSQL.