openapi-ts-json-schema
Generate TypeScript JSON schema files (.ts
) from OpenAPI definitions on Node.js.
TypeScript JSON schemas can natively be used for:
- Runtime data validation (with any JSON schema validator like Ajv)
- Static TypeScript type check (with
json-schema-to-ts
)
Given an OpenAPI definition file, openapi-ts-json-schema
will:
TypeScript JSON schemas are 100% valid JSON schemas.
Installation
npm i openapi-ts-json-schema -D
Usage
Generate your TypeScript JSON schemas:
import { openapiToTsJsonSchema } from 'openapi-ts-json-schema';
const { outputPath } = await openapiToTsJsonSchema({
openApiSchema: 'path/to/open-api-specs.yaml',
definitionPathsToGenerateFrom: ['paths', 'components.schemas'],
});
...then use them in your code:
import Ajv from 'ajv';
import type { FromSchema } from 'json-schema-to-ts';
import myGeneratedModelSchema from 'path/to/generated/schemas/MyModel.ts';
type MyModel = FromSchema<typeof myGeneratedModelSchema>;
const myModel: MyModel = { hello: 'World' };
const ajv = new Ajv();
const valid = ajv.validate(myGeneratedModelSchema, myModel);
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"] ). | - |
refHandling | "inline" | "import" | "keep" | "inline" : inline $ref schemas.
"import" : generate and import $ref schemas.
"keep" : keep $ref value. | "inline" |
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 . | - |
plugins | ReturnType<Plugin>[] | A set of optional plugin to generate any extra custom. See plugins docs. output. | - |
silent | boolean | Don't console.log user messages. | false |
Notes
Generated TypeScript JSON schema path names get escaped in order to be valid file system names.
Circular $ref
s can be technically resolved with "import" refHandling
option. But TS will stop the type recursion and type the schema as any
(error ts(7022)
). See relevant tests.
Take a look at the Developer's notes for a few more in-depth explanations.
Return values
Beside generating the expected schema files under outputPath
, openapiToTsJsonSchema
returns the following data:
{
outputPath: string;
metaData: {
schemas: Map<
string,
{
schemaId: string;
schemaFileName: string;
schemaAbsoluteDirName: string;
schemaAbsolutePath: string;
schemaAbsoluteImportPath: string;
schemaUniqueName: string;
schema: JSONSchema | string;
isRef: boolean;
}
>;
}
}
Plugins
Plugins are intended as a way to generate extra artifacts based on the same internal metadata created to generate the JSON schema output.
openapi-ts-json-schema
currently ships with one plugin specifically designed to better integrate with Fastify, but you can write your own!
Read plugins documentation 📖.
Todo
- Consider merging "operation" and "path" parameters definition
- Consider removing required
definitionPathsToGenerateFrom
option in favour of exporting the whole OpenAPI definitions based on the structure defined in specs - Consider adding a way to customize the values of the generated JSON schema ids. This could be beneficial even in case of multiple schemas being merged with plugins
- Find a way to merge multiple different OpenApi definitions consistently
- Improve external
#ref
s handling