Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

openapi-ts-json-schema

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

openapi-ts-json-schema

OpenAPI to JSON schema generator with TypeScript in mind

  • 0.7.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.3K
increased by6.09%
Maintainers
1
Weekly downloads
 
Created
Source

openapi-ts-json-schema

Build Status Npm version Coveralls

Generate TypeScript JSON schema files (.ts modules with as const assertions) from OpenAPI definitions.

TypeScript JSON schemas can be used for:

  • Inferring TypeScript type definitions from OpenApi definitions (with json-schema-to-ts)
  • Runtime data validation with TypeScript type inferring (with any JSON schema validator like Ajv)

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'],
});

...and use them in your TS project:

import Ajv from 'ajv';
import type { FromSchema } from 'json-schema-to-ts';
import mySchema from 'path/to/generated/schemas/MyModel.ts';

const ajv = new Ajv();
// Perform data validation and type inference using the same schema
const validate = ajv.compile<FromSchema<typeof mySchema>>(mySchema);
const data: unknown = {};

if (validate(data)) {
  // data gets type inference
  console.log(data.foo);
} else {
  console.log(validate.errors);
}

Options

PropertyTypeDescriptionDefault
openApiSchema (required)stringPath 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"import" | "inline" | "keep""import": generate and import $ref schemas.
"inline": inline $ref schemas.
"keep": keep $ref values.
"import"
schemaPatcher(params: { schema: JSONSchema }) => voidDynamically patch generated JSON schemas. The provided function will be invoked against every single JSON schema node.-
outputPathstringPath where the generated schemas will be saved. Defaults to /schemas-autogenerated in same directory as provided openApiSchema.-
pluginsReturnType<Plugin>[]A set of optional plugin to generate any extra custom. See plugins docs. output.-
silentbooleanDon't console.log user messages.false

Notes

Take a look at the Developer's notes for a few more in-depth explanations.

$refs handling

openapi-ts-json-schema provides 3 different strategies to handle OpenApi $ref properties configurable via the refHandling option:

  • import: $ref values get replaced with a local variable pointing to module of the generated target definition
  • inline: $ref values get recursively replaced with inline copies of the target definition. This produces self-contained standalone schemas with usually repeated inline definitions
  • keep: $ref values get preserved.

Circular $refs

Circular $refs can be technically resolved with "inline" and "import" refHandling option ("keep" doesn't resolve them by definition).

"inline" option replaces nested circular references with a {}.

"import" option fully resolves the tree but TS engine will interrupt type recursion and type the schema as any (error ts(7022)). See relevant tests.

Return values

Beside generating the expected schema files under outputPath, openapiToTsJsonSchema returns the following data:

{
  // The path where the schemas are generated
  outputPath: string;
  metaData: {
    // Meta data of the generated schemas
    schemas: Map<
      // OpenAPI ref. Eg: "#/components/schemas/MySchema"
      string,
      {
        schemaId: string;
        // JSON schema Compound Schema Document `$id`. Eg: `"/components/schemas/MySchema"`
        schemaFileName: string;
        // Valid filename for given schema (without extension). Eg: `"MySchema"`
        schemaAbsoluteDirName: string;
        // Absolute path pointing to schema folder. Eg: `"/output/path/components/schemas"`
        schemaAbsolutePath: string;
        // Absolute path pointing to schema file. Eg: `"/output/path/components/schemas/MySchema.ts"`
        schemaAbsoluteImportPath: string;
        // Absolute import path (without extension). Eg: `"/output/path/components/schemas/MySchema"`
        schemaUniqueName: string;
        // Unique JavaScript identifier used as import name. Eg: `"componentsSchemasMySchema"`
        schema: JSONSchema | string;
        // JSON schema value with $refs replaced by a placeholder
        isRef: boolean;
        // True if schemas is used as a `$ref`
      }
    >;
  }
}

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 #refs handling
  • Consider implementing an option to inline circular $refs with a configurable nesting level

Keywords

FAQs

Package last updated on 21 Feb 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc