openapi-ts-json-schema
Advanced tools
Comparing version 0.0.1 to 0.1.0
import { JSONSchema } from './utils'; | ||
export declare function openapiToTsJsonSchema({ openApiSchema: openApiSchemaRelative, definitionPathsToGenerateFrom, schemaPatcher, silent, }: { | ||
export declare function openapiToTsJsonSchema({ openApiSchema: openApiSchemaRelative, definitionPathsToGenerateFrom, schemaPatcher, outputPath: providedOutputPath, silent, }: { | ||
openApiSchema: string; | ||
definitionPathsToGenerateFrom?: string[]; | ||
definitionPathsToGenerateFrom: string[]; | ||
schemaPatcher?: (params: { | ||
schema: JSONSchema; | ||
}) => void; | ||
outputPath?: string; | ||
silent?: boolean; | ||
}): Promise<{ | ||
outputFolder: string; | ||
outputPath: string; | ||
}>; |
@@ -15,3 +15,6 @@ "use strict"; | ||
const utils_1 = require("./utils"); | ||
async function openapiToTsJsonSchema({ openApiSchema: openApiSchemaRelative, definitionPathsToGenerateFrom = [], schemaPatcher, silent, }) { | ||
async function openapiToTsJsonSchema({ openApiSchema: openApiSchemaRelative, definitionPathsToGenerateFrom = [], schemaPatcher, outputPath: providedOutputPath, silent, }) { | ||
if (definitionPathsToGenerateFrom.length === 0 && !silent) { | ||
console.log(`[openapi-ts-json-schema] ⚠️ No schemas will be generated since definitionPathsToGenerateFrom option is empty`); | ||
} | ||
const openApiSchemaPath = path_1.default.resolve(openApiSchemaRelative); | ||
@@ -21,4 +24,5 @@ if (!(0, fs_1.existsSync)(openApiSchemaPath)) { | ||
} | ||
const outputFolder = path_1.default.resolve(path_1.default.dirname(openApiSchemaPath), 'schemas-autogenerated'); | ||
await (0, utils_1.clearFolder)(outputFolder); | ||
const outputPath = providedOutputPath ?? | ||
path_1.default.resolve(path_1.default.dirname(openApiSchemaPath), 'schemas-autogenerated'); | ||
await (0, utils_1.clearFolder)(outputPath); | ||
const openApiSchema = await promises_1.default.readFile(openApiSchemaPath, 'utf-8'); | ||
@@ -28,4 +32,4 @@ const jsonOpenApiSchema = yaml_1.default.parse(openApiSchema); | ||
const dereferencedOpenApiSchema = await json_schema_ref_parser_1.default.dereference(jsonOpenApiSchema); | ||
// @NOTE path schema is converted by default | ||
const jsonSchema = (0, openapi_schema_to_json_schema_1.openapiSchemaToJsonSchema)(dereferencedOpenApiSchema, { | ||
// @NOTE paths schema is converted by default | ||
const jsonSchema = (0, openapi_schema_to_json_schema_1.fromSchema)(dereferencedOpenApiSchema, { | ||
definitionKeywords: definitionPathsToGenerateFrom, | ||
@@ -35,7 +39,7 @@ }); | ||
const schemas = (0, lodash_get_1.default)(jsonSchema, definitionPath); | ||
const schemasOutputFolder = path_1.default.resolve(outputFolder, definitionPath); | ||
const schemasoutputPath = path_1.default.resolve(outputPath, definitionPath); | ||
if (schemas) { | ||
await (0, utils_1.generateJsonSchemaFiles)({ | ||
schemas, | ||
outputFolder: schemasOutputFolder, | ||
outputPath: schemasoutputPath, | ||
schemaPatcher, | ||
@@ -46,6 +50,6 @@ }); | ||
if (!silent) { | ||
console.log(`✅ JSON schema models generated at ${outputFolder}`); | ||
console.log(`[openapi-ts-json-schema] ✅ JSON schema models generated at ${outputPath}`); | ||
} | ||
return { outputFolder }; | ||
return { outputPath }; | ||
} | ||
exports.openapiToTsJsonSchema = openapiToTsJsonSchema; |
import { JSONSchema } from './'; | ||
export declare function generateJsonSchemaFiles({ schemas, outputFolder, schemaPatcher, }: { | ||
export declare function generateJsonSchemaFiles({ schemas, outputPath, schemaPatcher, }: { | ||
schemas: Record<string, JSONSchema>; | ||
outputFolder: string; | ||
outputPath: string; | ||
schemaPatcher?: (params: { | ||
@@ -6,0 +6,0 @@ schema: JSONSchema; |
@@ -11,3 +11,3 @@ "use strict"; | ||
const _1 = require("./"); | ||
async function generateJsonSchemaFiles({ schemas, outputFolder, schemaPatcher, }) { | ||
async function generateJsonSchemaFiles({ schemas, outputPath, schemaPatcher, }) { | ||
for (const schemaName in schemas) { | ||
@@ -17,7 +17,8 @@ const schemaNamedEscaped = (0, filenamify_1.default)(schemaName, { replacement: '|' }); | ||
const patchedSchema = (0, _1.patchJsonSchema)(schema, schemaPatcher); | ||
(0, _1.convertOpenApiParameters)(patchedSchema); | ||
const tsSchema = await (0, _1.jsonSchemaToTsConst)(patchedSchema); | ||
await promises_1.default.mkdir(outputFolder, { recursive: true }); | ||
await promises_1.default.writeFile(path_1.default.resolve(outputFolder, `${schemaNamedEscaped}.ts`), tsSchema); | ||
await promises_1.default.mkdir(outputPath, { recursive: true }); | ||
await promises_1.default.writeFile(path_1.default.resolve(outputPath, `${schemaNamedEscaped}.ts`), tsSchema); | ||
} | ||
} | ||
exports.generateJsonSchemaFiles = generateJsonSchemaFiles; |
@@ -5,2 +5,3 @@ export { patchJsonSchema } from './patchJsonSchema'; | ||
export { generateJsonSchemaFiles } from './generateJsonSchemaFiles'; | ||
export { JSONSchema } from './types'; | ||
export { convertOpenApiParameters } from './convertOpenApiParameters'; | ||
export type { JSONSchema } from './types'; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.generateJsonSchemaFiles = exports.jsonSchemaToTsConst = exports.clearFolder = exports.patchJsonSchema = void 0; | ||
exports.convertOpenApiParameters = exports.generateJsonSchemaFiles = exports.jsonSchemaToTsConst = exports.clearFolder = exports.patchJsonSchema = void 0; | ||
var patchJsonSchema_1 = require("./patchJsonSchema"); | ||
@@ -12,1 +12,3 @@ Object.defineProperty(exports, "patchJsonSchema", { enumerable: true, get: function () { return patchJsonSchema_1.patchJsonSchema; } }); | ||
Object.defineProperty(exports, "generateJsonSchemaFiles", { enumerable: true, get: function () { return generateJsonSchemaFiles_1.generateJsonSchemaFiles; } }); | ||
var convertOpenApiParameters_1 = require("./convertOpenApiParameters"); | ||
Object.defineProperty(exports, "convertOpenApiParameters", { enumerable: true, get: function () { return convertOpenApiParameters_1.convertOpenApiParameters; } }); |
@@ -1,4 +0,4 @@ | ||
import { JSONSchema } from './'; | ||
import type { JSONSchema } from './'; | ||
export declare function patchJsonSchema(schema: JSONSchema, schemaPatcher?: (params: { | ||
schema: JSONSchema; | ||
}) => void): JSONSchema; |
@@ -11,2 +11,3 @@ "use strict"; | ||
(0, json_schema_traverse_1.default)(schema, { | ||
allKeys: true, | ||
cb: (schema) => { | ||
@@ -13,0 +14,0 @@ schemaPatcher({ schema }); |
{ | ||
"name": "openapi-ts-json-schema", | ||
"version": "0.0.1", | ||
"description": "Convert OpenApi definitions to TS JSON schema files", | ||
"version": "0.1.0", | ||
"description": "OpenAPI to JSON schema generator with TypeScript in mind", | ||
"main": "./dist/index.js", | ||
@@ -13,6 +13,5 @@ "types": "./dist/index.d.ts", | ||
"test": "vitest --config ./vitest.config.mts --dir ./test", | ||
"preversion": "npm run prepare", | ||
"version": "git add package.json", | ||
"postversion": "git push && git push --tags", | ||
"prepare": "npx simple-git-hooks", | ||
"prepare": "npx simple-git-hooks && npm run test -- --run && npm run source:check && npm run build", | ||
"tag": "git tag v$(node -p \"require('./package.json').version\")", | ||
"posttag": "git push --tags", | ||
"prettier:check": "prettier . --check", | ||
@@ -24,3 +23,9 @@ "prettier:fix": "npm run prettier:check -- --write", | ||
}, | ||
"keywords": [], | ||
"keywords": [ | ||
"openapi", | ||
"json", | ||
"schema", | ||
"typescript", | ||
"openapi to json schema" | ||
], | ||
"repository": { | ||
@@ -36,8 +41,8 @@ "type": "git", | ||
"@types/lodash.get": "^4.4.7", | ||
"@vitest/coverage-v8": "^0.33.0", | ||
"@vitest/coverage-istanbul": "^0.34.1", | ||
"rimraf": "^5.0.1", | ||
"simple-git-hooks": "^2.8.1", | ||
"simple-git-hooks": "^2.9.0", | ||
"tiny-glob": "^0.2.9", | ||
"typescript": "^5.1.6", | ||
"vitest": "^0.33.0" | ||
"vitest": "^0.34.1" | ||
}, | ||
@@ -57,5 +62,6 @@ "engines": { | ||
"lodash.get": "^4.4.2", | ||
"prettier": "^3.0.0", | ||
"openapi-jsonschema-parameters": "^12.1.3", | ||
"prettier": "^3.0.1", | ||
"yaml": "^2.3.1" | ||
} | ||
} |
# 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`](https://github.com/ThomasAribart/json-schema-to-ts) or [`fastify-type-provider-json-schema-to-ts`](https://github.com/fastify/fastify-type-provider-json-schema-to-ts)). | ||
[![Build Status][ci-badge]][ci] | ||
[![Npm version][npm-version-badge]][npm] | ||
[![Coveralls][coveralls-badge]][coveralls] | ||
Generate JSON schema TypeScript files (`.ts`) from OpenAPI definitions which can be natively used to infer types from (with [`json-schema-to-ts`](https://github.com/ThomasAribart/json-schema-to-ts) or [`fastify-type-provider-json-schema-to-ts`](https://github.com/fastify/fastify-type-provider-json-schema-to-ts)). | ||
Given an OpenAPI definition file, `openapi-ts-json-schema` will: | ||
- Dereference the definitions with [`@apidevtools/json-schema-ref-parser`](https://github.com/APIDevTools/json-schema-ref-parser) (resolving `$ref`'s) | ||
- Convert to JSON schema with [`@openapi-contrib/openapi-schema-to-json-schema`](https://github.com/openapi-contrib/openapi-schema-to-json-schema) | ||
- Generate a TypeScript JSON schema file for each definition (`.ts` files with `as const` assertion) | ||
- Convert to JSON schema with [`@openapi-contrib/openapi-schema-to-json-schema`](https://github.com/openapi-contrib/openapi-schema-to-json-schema) and [`openapi-jsonschema-parameters`](https://www.npmjs.com/package/openapi-jsonschema-parameters) | ||
- Generate one TypeScript JSON schema file for each definition (`.ts` files with `as const` assertion) | ||
- Store schemas in a folder structure reflecting the original OpenAPI definition structure | ||
@@ -23,4 +27,4 @@ | ||
const { outputFolder } = await openapiToTsJsonSchema({ | ||
openApiSchema: path.resolve(fixtures, 'path/to/my/specs.yaml'), | ||
const { outputPath } = await openapiToTsJsonSchema({ | ||
openApiSchema: 'path/to/open-api-specs.yaml', | ||
definitionPathsToGenerateFrom: ['paths', 'components.schemas'], | ||
@@ -35,9 +39,9 @@ }); | ||
import { FromSchema } from 'json-schema-to-ts'; | ||
import myModelSchema from './definitions/schemas-autogenerated/MyModel.ts'; | ||
import myModelSchema from 'path/to/schemas-autogenerated/MyModel.ts'; | ||
// Use generated JSON schemas | ||
// Use generated JSON schemas as usual | ||
const ajv = new Ajv(); | ||
const valid = ajv.validate(myModelSchema, {}); | ||
const valid = ajv.validate(myModelSchema, { hello: 'World' }); | ||
// Infer types from generated JSON schemas | ||
// Use generated JSON schemas to infer model types from | ||
type MyModel = FromSchema<typeof myModelSchema>; | ||
@@ -48,14 +52,13 @@ ``` | ||
Generated JSON schemas folders get currently saved in a `schemas-autogenerated` folder next to the provided OpenAPI definition file. | ||
Generated JSON schema path names get escaped in order to be valid file system names. | ||
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` | | ||
| 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` | | ||
@@ -65,1 +68,10 @@ ## 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 | ||
[ci-badge]: https://github.com/toomuchdesign/openapi-ts-json-schema/actions/workflows/ci.yml/badge.svg | ||
[ci]: https://github.com/toomuchdesign/openapi-ts-json-schema/actions/workflows/ci.yml | ||
[coveralls-badge]: https://coveralls.io/repos/github/toomuchdesign/openapi-ts-json-schema/badge.svg?branch=master | ||
[coveralls]: https://coveralls.io/github/toomuchdesign/openapi-ts-json-schema?branch=master | ||
[npm]: https://www.npmjs.com/package/openapi-ts-json-schema | ||
[npm-version-badge]: https://img.shields.io/npm/v/openapi-ts-json-schema.svg |
18134
21
208
74
9
+ Addedopenapi-jsonschema-parameters@12.1.3(transitive)
+ Addedopenapi-types@12.1.3(transitive)
Updatedprettier@^3.0.1