UNPKG

openapi-ts-json-schema

Version:

OpenAPI to JSON schema generator with TypeScript in mind

57 lines (56 loc) 2.36 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.convertOpenApiToJsonSchema = void 0; const map_obj_1 = __importDefault(require("map-obj")); const openapi_schema_to_json_schema_1 = require("@openapi-contrib/openapi-schema-to-json-schema"); const _1 = require("./"); function convertToJsonSchema(value) { if (!(0, _1.isObject)(value)) { return value; } /** * Skip openAPI parameters since conversion causes data loss (they are not valid JSON schema) * which makes impossible to aggregate them into JSON schema. * * Conversion is carried out later with "convertOpenApiPathsParameters" */ if ((0, _1.isOpenApiParameterObject)(value)) { return value; } try { const schema = (0, openapi_schema_to_json_schema_1.fromSchema)(value, { strictMode: false }); // $schema is appended by @openapi-contrib/openapi-schema-to-json-schema delete schema.$schema; return schema; } catch (error) { /* v8 ignore next 1 */ const errorMessage = error instanceof Error ? error.message : ''; throw new Error(`[openapi-ts-json-schema] OpenApi to JSON schema conversion failed: "${errorMessage}"`, { cause: value }); } } /** * Traverse the openAPI schema tree an brutally try to convert every oas definition * to JSON schema. We are probably overdoing since we process any found object. * * - Is there a way to tell an OpenAPI definition objects convertible to JSON schema from the others? * - Could we explicitly convert only the properties that need it? * * @TODO Find a nicer way to convert convert all the expected OpenAPI schemas */ function convertOpenApiToJsonSchema(schema) { return (0, map_obj_1.default)(schema, (key, value) => { /** * @NOTE map-obj only processes object values separately */ if (Array.isArray(value)) { return [key, value.map((entry) => convertToJsonSchema(entry))]; } // @NOTE map-obj transforms only arrays entries which are objects return [key, convertToJsonSchema(value)]; }, { deep: true }); } exports.convertOpenApiToJsonSchema = convertOpenApiToJsonSchema;