@ibabkin/openapi-express-server
v3.2.0
Published
Express.js server implementation for OpenAPI-generated interfaces
Maintainers
Readme
@ibabkin/openapi-express-server
Express.js building blocks for wiring routes from an OpenAPI spec to use cases resolved from a
ts-ioc-container scope. Pairs with
@ibabkin/openapi-to-server (one <Op>HttpRoute interface per operation) and @ibabkin/openapi-to-zod
(Zod payload validators).
Exports
extractRoutes(spec)— flattens anOpenAPIV3.DocumentintoRouteMetadata[](path,method,operationId,tags);operationIdis the DI key of the operation's use case,tagsare the operation's tags verbatimconvertOpenAPIPathToExpress(path)—/users/{id}→/users/:idbuildPayload(req)— picksparams,query,body,headersoff an Express requestcontainerMiddleware(appContainer, tags?)— creates a request-scoped child container tagged['request', ...tags], attaches it toreq.container, and disposes it when the response finishes. Mount it per route withroute.tagsso registrations bound to a tag (scope((s) => s.hasTag('admins'))) apply to exactly the operations carrying itgetContainerOrFail(req)— readsreq.containeror throws
Usage
Register one use case per operation in an application container, keyed by its operationId, then register one
Express route per operation. A reference RouteBuilder that does exactly this lives in
__tests__/RouteBuilder.ts:
import 'reflect-metadata';
import express from 'express';
import { Container, Registration } from 'ts-ioc-container';
import { PAYLOADS } from './generated-validators';
import { RouteBuilder } from './RouteBuilder';
const container = new Container({ tags: ['application'] });
container.addRegistration(Registration.fromClass(GetUsers).bindToKey('getUsers'));
container.addRegistration(Registration.fromClass(CreateUser).bindToKey('createUser'));
const app = express();
app.use(express.json());
container.resolve(RouteBuilder, { args: [spec, PAYLOADS] }).applyTo(app);
app.use((error, req, res, next) => {
res.status(error instanceof ZodError ? 400 : 500).json({ error: error.message });
});Each route mounts containerMiddleware(container, route.tags), so every request gets a scope tagged with
request and the operation's tags. The handler resolves the use case from that scope under the operationId,
validates req with the Zod schema for the same operationId, calls useCase.handle(payload, scope), and writes
{ status, headers, body } to the response.
For AI agents
The package ships AGENTS.md, a compact guide for coding agents: the one-route-per-operation wiring recipe (exercised by __tests__/agentGuides.spec.ts), the request-scope model and the pitfalls. After
installation it is at node_modules/@ibabkin/openapi-express-server/AGENTS.md. Point your agent at it from your own
AGENTS.md or CLAUDE.md.
Development
pnpm build
pnpm test__tests__/integration/generated.spec.ts generates types and validators from __tests__/integration/api.yaml at
test time and runs an end-to-end server against them.
License
ISC
