openapi-ts-json-schema
Generate JSON schemas 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 { outputFolder } = await openapiToTsJsonSchema({
openApiSchema: path.resolve(fixtures, 'path/to/my/specs.yaml'),
definitionPathsToGenerateFrom: ['paths', 'components.schemas'],
});
...then in your code:
import Ajv from 'ajv';
import { FromSchema } from 'json-schema-to-ts';
import myModelSchema from './definitions/schemas-autogenerated/MyModel.ts';
const ajv = new Ajv();
const valid = ajv.validate(myModelSchema, {});
type MyModel = FromSchema<typeof myModelSchema>;
Notes
Generated JSON schemas folders get currently saved in a schemas-autogenerated
folder next to the provided OpenAPI definition file.
Generated JSON schemas folders name gets 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 | 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. | - |
silent | boolean | Don't console.log user messages | false |
Todo
- Consider exposing an option to set the output folder path