One job per desk: requests, responses, and handlers
Every action in Porchlight has the same shape. Filing a report, saving a post, sending a sign-in email: a request goes in, one handler does the job, and a response comes out. This post shows what that looks like and why it helps.
Think of a mail room. Each kind of envelope goes to one desk. The mail room never opens a letter. It only knows which desk gets which envelope. The desk does the work and sends back an answer.
The envelope: a request
A request is a small class that holds what the job needs. Here is the one for filing a report, trimmed a little:
export class FileReportRequest extends RequestBase {
constructor(
readonly reporterId: string | null,
readonly target: ModerationTarget,
readonly reason: ReportReason,
readonly details: string | null,
readonly startsEscalated: boolean,
) {
super();
}
}
There is no type: "file-report" field. The class itself is the label. Every request also gets an id and a time stamp from RequestBase, so one action can be followed through the logs from start to finish.
The desk: a handler
A handler does one job for one kind of request. The rule is one handler per file, with all of its logic inside:
export interface IHandler<TRequest, TResponse> {
readonly handle: (request: TRequest) => Promise<TResponse>;
}
The handler that saves a report to the database looks like this, again trimmed:
export class SupabaseFileReportHandler implements IHandler<
FileReportRequest,
ReportStoredResponse | ReportAlreadyOpenResponse | ReportAccessFailedResponse
> {
constructor(private readonly db: DbClient) {}
async handle(request: FileReportRequest) {
const { data, error } = await this.db
.from("reports")
.insert({ /* the request's fields */ })
.select(REPORT_COLUMNS)
.single();
if (error) {
return error.code === UNIQUE_VIOLATION
? new ReportAlreadyOpenResponse(request.correlationId)
: new ReportAccessFailedResponse(request.correlationId, error.message);
}
return new ReportStoredResponse(request.correlationId, toReport(data));
}
}
It knows about reports and nothing else.
The mail room: the resolver
The resolver is a lookup table from a request's class to its handler. It is almost too short to be interesting:
async resolve(request: RequestBase): Promise<ResponseBase> {
const dispatch = this.dispatches.get(request.constructor);
const pending = dispatch?.(request);
if (pending === undefined) {
return new UnhandledRequestResponse(
request.correlationId,
request.constructor.name,
);
}
return pending;
}
The part of the code that talks to reports is just a shell around two of these tables, one for writes and one for reads:
export class ReportAccessor implements IReportAccessor {
constructor(
private readonly storeResolver: HandlerResolver,
private readonly loadResolver: HandlerResolver,
) {}
store(request: RequestBase) {
return this.storeResolver.resolve(request);
}
load(request: RequestBase) {
return this.loadResolver.resolve(request);
}
}
Wiring it all in one place
Every desk gets its envelopes in one file, when the app starts. For reports, there are two versions of that wiring: one for the real database and one fake that keeps everything in memory.
function createSupabaseReportAccessor(db: DbClient) {
return new ReportAccessor(
new HandlerResolverBuilder()
.register(FileReportRequest, new SupabaseFileReportHandler(db))
.register(ResolveReportsForTargetRequest, new SupabaseResolveReportsForTargetHandler(db))
.build(),
new HandlerResolverBuilder()
.register(ListReportsRequest, new SupabaseListReportsHandler(db))
.build(),
);
}
function createFakeReportAccessor(state: FakeReportState) {
return new ReportAccessor(
new HandlerResolverBuilder()
.register(FileReportRequest, new FakeFileReportHandler(state))
.register(ResolveReportsForTargetRequest, new FakeResolveReportsForTargetHandler(state))
.build(),
new HandlerResolverBuilder()
.register(ListReportsRequest, new FakeListReportsHandler(state))
.build(),
);
}
One setting picks which one to build.
Why it is worth it
You can swap what is behind a desk
The code that files a report does not know whether the report goes to a real database or to a list in memory. It sends the same envelope either way. That is how Porchlight runs on a laptop with no accounts and no keys for any outside service, and how the tests run fast without a real database. The fake handlers even act like the real ones: the fake report handler refuses a second open report from the same person for the same reason, just as the database does.
Every answer has its own shape
A response is never "success: true or false, plus maybe a message." Each outcome is its own class. Filing a report can come back three ways: stored, already open, or failed. The caller checks which one it got:
const stored = await this.reports.store(new FileReportRequest(/* ... */));
if (stored instanceof ReportAlreadyOpenResponse) {
return new ReportAlreadyFiledResponse(correlationId);
}
if (!(stored instanceof ReportStoredResponse)) {
return unavailable(correlationId, stored, "reports.store");
}
// From here on, TypeScript knows `stored.report` exists.
stored.report.id;
"You already reported this" is a normal answer, not an error. It gets its own class, so it is hard to forget. And once the code has checked for a stored report, the report is simply there. There is no field that might be empty.
New features add files instead of editing old ones
To add a new action, you write a new request, a new handler, and the responses it can give. Then you add one line to the wiring. No existing handler changes. There is no giant switch statement that every feature has to squeeze into.
Porchlight's core has about 215 request files, 330 handler files, and 286 response files. That sounds like a lot, and it is. But each file is small, does one thing, and can be read without opening anything else.
Mistakes are loud
If a request reaches a resolver with no handler for it, the answer is UnhandledRequestResponse, and the site turns it into a server error instead of quietly doing nothing. If the wiring tries to give one kind of request two handlers, the app refuses to start:
if (this.dispatches.has(requestType)) {
throw new Error(`${requestType.name} already has a handler on this resolver`);
}
The compiler catches another class of mistake. You cannot register a handler for one kind of request under a different kind. The handle in IHandler is written as a property on purpose, not a method, because TypeScript checks the two differently. Written as a method, the wrong pairing would compile and then crash later.
What it costs
- Many files. Saving one row can mean five or six files: the request, the handler, a fake handler, and a response for each outcome.
- Ceremony for small jobs. A job that is one line of code still gets its own envelope and desk.
- An extra step to follow the code. You cannot click from the caller straight into the handler, because the resolver sits in between. You look up the request's class in the wiring file instead.
For a project where every outside service has to be swappable, and every screen has a test that runs without the real service, those costs have been worth paying.
Drafted with an assistant, edited by @wintaru
0 comments