A route handler that validates the request, applies the business rules, reads and writes the database, and formats the response is doing four jobs, and you cannot test any one of them without standing up all four. The fix is not a rewrite. It is a sequence of small, boring extractions that never leave the application broken.
Every codebase acquires a few of these. A controller method starts as five honest lines, then a validation branch lands, then a pricing rule, then a second write, and eighteen months later it is a 120-line method that only runs inside an HTTP request. Nobody unit-tests it because there is nothing to unit-test in isolation. So it grows, and the same rules get copied into the next endpoint that needs them. This is a field note on getting the business logic out of a bloated NestJS handler and into a service layer you can actually test, without the big-bang rewrite that never ships. Examples are NestJS 10 on Node 22, TypeScript 5, tests in Jest.
What a fat controller actually looks like
Here is the shape of the problem, trimmed but not caricatured. The handler parses the body by hand, computes a total, applies an approval threshold, writes the row, and shapes the response, all in one place.
Free · 4 minutes
Do you actually know what you are running — and what it is about to cost you?
Fourteen questions on the systems you depend on, the ones nobody owns, and the support dates that turn a routine upgrade into a forced re-platform. Banded finding on screen, full sheet by email.
// orders.controller.ts — before
@Controller('orders')
export class OrdersController {
constructor(private readonly dataSource: DataSource) {}
@Post()
async create(@Body() body: any, @Res() res: Response) {
// validation
if (!body.customerId || !Array.isArray(body.lines) || body.lines.length === 0) {
return res.status(400).json({ error: 'invalid order' });
}
// business rule: total and approval threshold
let total = 0;
for (const line of body.lines) {
total += line.qty * line.unitPrice;
}
const status = total > 10_000 ? 'PENDING_APPROVAL' : 'CONFIRMED';
// data access
const repo = this.dataSource.getRepository(Order);
const order = await repo.save({ customerId: body.customerId, total, status });
// response formatting
return res.status(201).json({ id: order.id, total, status });
}
}
The tell is the mixed vocabulary in one method: HTTP words (@Res, status codes), domain words (approval threshold), and persistence words (getRepository, save). Each belongs in a different layer. And because the approval rule lives inside an Express-style handler, the only way to exercise it is a full HTTP round trip against a real or mocked database.
Lock the behaviour before you touch it
The refactor is only safe if you can prove the endpoint still does what it did. Before extracting anything, write characterisation tests: tests that assert the current behaviour, including any behaviour you suspect is a bug. You are not deciding what the code should do; you are pinning down what it does do, so that a change of shape cannot become a silent change of behaviour.
Cover the branches that matter: a valid order under the threshold, a valid order over it, an empty lines array, a missing customerId. Assert the status code and the exact response body. Run them green against the fat controller first. If you cannot get them green, that is your answer about how well the current behaviour is understood, and it is worth knowing before you start moving code.
These tests are scaffolding. Some will be deleted once cleaner unit tests exist against the service; their job is to hold the line during the move. This is the same discipline as any incremental migration — you keep the old path working while the new one grows beside it, which is exactly the logic behind a strangler-fig approach over a big-bang cutover.
Find the seam and inject it
A seam is a place where you can change behaviour without editing the code around it. The fat controller has no seam: it news up its dependency by reaching through DataSource. The first structural move is to put an interface between the logic and the persistence, so the business rules can be tested against a fake repository with no database at all.
// order-repository.interface.ts
export interface OrderRecord {
customerId: string;
total: number;
status: 'CONFIRMED' | 'PENDING_APPROVAL';
}
export interface OrderRepository {
save(order: OrderRecord): Promise<OrderRecord & { id: string }>;
}
export const ORDER_REPOSITORY = Symbol('ORDER_REPOSITORY');
Now the service: it takes the parsed input, applies the rules, calls the repository through the interface, and returns a plain object. No decorators from the HTTP layer, no Response, no framework request in sight.
// orders.service.ts — after
@Injectable()
export class OrdersService {
constructor(
@Inject(ORDER_REPOSITORY) private readonly orders: OrderRepository,
) {}
async createOrder(input: CreateOrderDto) {
const total = input.lines.reduce(
(sum, line) => sum + line.qty * line.unitPrice,
0,
);
const status = total > 10_000 ? 'PENDING_APPROVAL' : 'CONFIRMED';
const saved = await this.orders.save({
customerId: input.customerId,
total,
status,
});
return { id: saved.id, total, status };
}
}
The controller shrinks to its real job: parse, call, respond. Validation moves to a DTO with class-validator, so an invalid body is rejected by the framework before the method body runs, and the handler no longer hand-rolls a 400.
// orders.controller.ts — after
@Controller('orders')
export class OrdersController {
constructor(private readonly ordersService: OrdersService) {}
@Post()
@HttpCode(201)
create(@Body() dto: CreateOrderDto) {
return this.ordersService.createOrder(dto);
}
}
Wire the real TypeORM repository to the token in the module with useClass or useValue, and the production path is unchanged while the service is now testable in complete isolation. The approval rule that used to need an HTTP round trip is now three lines and a fake:
// orders.service.spec.ts
it('flags orders over the threshold for approval', async () => {
const saved: OrderRecord[] = [];
const fake: OrderRepository = {
save: async (o) => { saved.push(o); return { ...o, id: 'o1' }; },
};
const service = new OrdersService(fake);
const result = await service.createOrder({
customerId: 'c1',
lines: [{ qty: 3, unitPrice: 4_000 }],
});
expect(result.status).toBe('PENDING_APPROVAL');
expect(result.total).toBe(12_000);
});
Keep the handler to parse, call, respond
The rule of thumb that keeps controllers thin: a handler may read the request, call exactly one service method, and shape the result into a response. It may not contain a business decision. The moment a controller has an if that changes a domain outcome — a threshold, an eligibility check, a state transition — that logic belongs in the service, where it can be tested and reused. Cross-cutting concerns that are genuinely HTTP-shaped, like turning a domain error into a 409, are fine in an exception filter or interceptor rather than smuggled back into the handler.
Do this one endpoint at a time. Extract, keep the characterisation tests green, ship, move on. You are never holding a half-migrated branch open for three weeks, which is the failure mode that turns an incremental refactor back into a big-bang rewrite by the back door. Firms modernising a live system under regulatory and client-service pressure lean on exactly this property — the ability to modernise a core without breaking the service running on top of it.
Where to stop
There is a point of diminishing returns, and it is worth naming so nobody chases layers for their own sake. Extract to a service when logic is duplicated, when it carries a real business rule, or when it is genuinely hard to test through the controller. Do not manufacture a service for a handler that reads one row and returns it — a passthrough service that only calls one repository method adds a file and a hop and buys nothing. Not every endpoint needs a service; the ones with rules do.
The signal you are done is boring in the best way: business rules sit in services with fast unit tests, data access hides behind an interface, and controllers are short enough that reviewing one tells you the whole story. If a new rule has an obvious home the first time someone asks where it goes, the layer is doing its job. That clarity is the same payoff as designing the boundary up front, which is why a well-shaped service layer and a contract-first API surface tend to arrive together. Refactor towards the seam, not towards a diagram.
Build and rescue work
Hands-on delivery of this kind is handled by Sixteen Pillars Studio.
Free interactive tool
Website compliance checklist
What your site has to do, based on what it actually does
Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.
Everything that applies
Ordered by what to do first: legal requirements you can close quickly, then larger pieces of work, then what is expected rather than required. Not exhaustive, and not a legal audit.
Dated PDF, yours to keep or circulate.
Most technology problems are not technology problems. They are control problems.
The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.