This package is meant to provide a typed Express router for an OpenAPI spec. Based on the oatx
library and adapted to override Express values.
-
Run
yarn --cwd <package-dir> backstage-cli package schema openapi generate
to translate yoursrc/schema/openapi.yaml
to a new Typescript file insrc/schema/openapi.generated.ts
. The command will try to execute both a lint and prettier step on the generated file, where applicable. -
In your plugin's
src/service/createRouter.ts
,
import { ApiRouter } from `@backstage/backend-openapi-utils`;
import spec from '../schema/openapi.generated';
// ...
export function createRouter() {
const router = Router() as ApiRouter<typeof spec>;
// ...
return router;
}
as const
makes all fieldsreadonly
To ensure a good DX of using a simple imported JSON spec, we want to remove any type issues betweenreadonly
arrays and mutable arrays. Typescript does not allow them to be compared, so converting all imports from theopenapi3-ts
library toreadonly
is important. This is achieved through theImmutableObject
type intypes/immutable.ts
.
...
// We want an interface like this,
Router() as ApiRouter<typeof spec>
// Not an interface like this,
Router() as ApiRouter<DeepWriteable<typeof spec>>
...
Using a package like express-openapi-validator
, would allow us to remove validation of request bodies with AJV
. However, AJV
currently doesn't have support for OpenAPI 3.1 and express-openapi-validator
enforces full URL matching for paths, meaning it cannot be mounted at the router level.