openapi-ts-json-schema
Generate JSON schema TypeScript files (.ts
) from OpenAPI definitions which can be natively used to infer types from (with json-schema-to-ts
or fastify-type-provider-json-schema-to-ts
).
Given an OpenAPI definition file, openapi-ts-json-schema
will:
Installation
npm i openapi-ts-json-schema -D
Usage
import { openapiToTsJsonSchema } from 'openapi-ts-json-schema';
const { outputPath } = await openapiToTsJsonSchema({
openApiSchema: 'path/to/open-api-specs.yaml',
definitionPathsToGenerateFrom: ['paths', 'components.schemas'],
});
...then in your code:
import Ajv from 'ajv';
import { FromSchema } from 'json-schema-to-ts';
import myModelSchema from 'path/to/schemas-autogenerated/MyModel.ts';
const ajv = new Ajv();
const valid = ajv.validate(myModelSchema, { hello: 'World' });
type MyModel = FromSchema<typeof myModelSchema>;
Notes
Generated JSON schema path names get escaped in order to be valid file system names.
Options
Property | Type | Description | Default |
---|
openApiSchema (required) | string | Path to the OpenApi file (supports yaml and json). | - |
definitionPathsToGenerateFrom (required) | string[] | OpenApi definition object paths to generate the JSON schemas from. Only matching paths will be generated. (Supports dot notation: ["components.schemas"] ). | - |
schemaPatcher | (params: { schema: JSONSchema }) => void | Dynamically patch generated JSON schemas. The provided function will be invoked against every single JSON schema node. | - |
outputPath | string | Path where the generated schemas will be saved. Defaults to /schemas-autogenerated in same directory as provided openApiSchema . | - |
silent | boolean | Don't console.log user messages. | false |
Todo
- Consider exposing an option to set the output folder path
- Explore ability to import shared sub schemas
- Consider merging "operation" and "path" parameters definition