In the last lesson, the problem list got a schema for its query, and GET /problems started responding with 400 for a limit of abc. That check now sits inside its handler, next to the body check in POST /problems. Each one is a .safeParse() call and an error response, and the route’s real work only starts after them. PATCH /problems/:id still checks retired by hand, and ProblemParams isn’t used yet.
In this lesson, you’ll move those checks into validate(), one function that builds the validation middleware for whatever schemas a route gives it. You’ll decide where the checked data goes so the handlers can read it, and you’ll give PATCH a schema of its own. Start with the question of how one middleware function can know which schema to use.
Build validate() as a Middleware Factory
The two checks you have are the same apart from three things: the schema, the part of the request it checks, and the status code for a failure. Middleware is the right place for them, because it runs before the handler and can send the response itself. However, Express calls every middleware function with req, res, and next, and nothing else. There’s no slot for a schema.
The way around that is a function that takes the schemas and returns the middleware. A function like this is a middleware factory. Calling validate({ query: ProblemQuery }) doesn’t check anything. It builds a new middleware function that checks the query against ProblemQuery, and the route lists that function. Each route can call validate() with its own schemas and get its own checker.
Start with what the factory needs to know. In middleware.ts, import z and the two helpers from responses.ts, then describe the schemas a route can pass:
middleware.ts
import type { NextFunction, Request, Response } from "express";
import { z } from "zod";
import { errorBody, readJsonBody } from "./responses.ts";
// ...
type Schemas = {
params?: z.ZodType;
query?: z.ZodType;
body?: z.ZodType;
};
const sources = ["params", "query", "body"] as const;
const messages = {
params: "Check the path values listed in details.",
query: "Check the query values listed in details.",
body: "Check the fields listed in details.",
};
z.ZodType is the type of any Zod schema, and each source is optional, so a route passes only the schemas it needs. The sources array names the three parts of a request in the order they’re checked: the path parameters, the query string, and then the body. With as const, TypeScript knows the array holds exactly those three strings, so it can check schemas[source] and req[source] in the loop below.
Add the factory itself at the bottom of middleware.ts:
middleware.ts
export function validate(schemas: Schemas) {
return (req: Request, res: Response, next: NextFunction) => {
for (const source of sources) {
const schema = schemas[source];
if (schema === undefined) {
continue;
}
if (source === "body" && readJsonBody(req, res) === undefined) {
return;
}
const result = schema.safeParse(req[source]);
if (!result.success) {
const status = source === "body" ? 422 : 400;
const details = z.flattenError(result.error);
res.status(status).json(
errorBody(`invalid_${source}`, messages[source], details),
);
return;
}
// Store result.data for the handler here.
}
next();
};
}
validate() returns an arrow function with the familiar (req, res, next) parameters. That function runs once per request, long after validate() has returned, and it can still read schemas because it’s a closure: a function keeps access to the variables in the scope where it was created.
For each source with a schema, the loop does what your handlers did:
- The body first goes through the checks in
readJsonBody(). They respond with415for a body that isn’t sent as JSON and400withempty_bodyfor no body at all. WhenreadJsonBody()has responded, it returnsundefined, and the middleware stops. - A failed parse reports every problem by field, through
errorBody()andz.flattenError(), as before. The status follows the API’s rule:400for a query or path value it refuses,422for a body that breaks the rules. - A successful parse leaves the checked values in
result.data, and the loop moves on to the next source. Once every source passes,next()hands the request to the handler. The comment marks the one decision left, which is where to storeresult.data, and you’ll make it in the next section.
That empty_body check has a gap. express.json() turns a JSON request with a zero-length body into {}, so req.body is undefined only when no body was sent at all. An empty POST would get a 422 that lists every field, and an empty PATCH would pass. A client that sends an empty body still sends a Content-Length of 0, so check that header too in readJsonBody() in responses.ts:
responses.ts
const length = req.get("Content-Length");
if (req.body === undefined || length === "0") {
An explicit {} has a length of 2, so it still reaches the schema. You’ll send an empty body once POST /problems lists validate().
The error code is now built from the source: invalid_params, invalid_query, or invalid_body. That last one replaces invalid_problem, because validate() doesn’t know what a body describes. If you’d like to see how the returned function holds on to its schemas, ask:
Hand the Parsed Data to the Handler
The handler needs the parsed data, where the limit is a number, the name is trimmed, and extra fields are gone. The middleware has it in result.data, so it has to leave it somewhere the handler can read. Where should it go?