openapi-json-schema
Version:
Minimalistic OpenAPI 3 ⬌ JSON Schema (draft 7) conversion
36 lines (35 loc) • 1.25 kB
JavaScript
import { decodeRefNameOpenApi, encodeRefNameJsonSchema, recurseSchema, } from './utils.js';
function openApiTypeToJsonSchema7Type(type, nullable) {
if (typeof type === "undefined" || type === "any")
return undefined; // Any-type includes null
else if (!Array.isArray(type))
return (type === "null" || !nullable)
? type
: [type, "null"];
else {
if (type.includes("any"))
return undefined; // Any-type includes null
if (!type.includes("null") && nullable)
type.push("null");
if (type.length === 1)
return type[0];
return type;
}
}
function openApiToJsonSchema7Ref(node) {
if (node.$ref)
return {
...node,
$ref: encodeRefNameJsonSchema(decodeRefNameOpenApi(node.$ref)),
};
return node;
}
export function openApiToJsonSchemaType(schema) {
if (typeof schema === 'boolean')
return schema;
const { type: _type, nullable, ...rest } = schema;
const type = openApiTypeToJsonSchema7Type(_type, nullable);
let output = { ...rest, ...(type ? { type } : {}) };
output = openApiToJsonSchema7Ref(output);
return recurseSchema(output, openApiToJsonSchemaType);
}