openapi-json-schema
Version:
Minimalistic OpenAPI 3 ⬌ JSON Schema (draft 7) conversion
80 lines (79 loc) • 3.46 kB
JavaScript
export function encodePathPart(part) {
return encodeURIComponent(part);
}
export function decodePathPart(part) {
return decodeURIComponent(part);
}
export function encodeRefNameJsonSchema(name) {
return `#/definitions/${encodePathPart(name)}`;
}
export function decodeRefNameJsonSchema(name) {
if (name.startsWith("#/definitions/"))
return decodePathPart(name.slice(14));
return decodePathPart(name);
}
export function encodeRefNameOpenApi(name) {
return `#/components/schemas/${encodePathPart(name)}`;
}
export function decodeRefNameOpenApi(name) {
if (name.startsWith("#/components/schemas/"))
return decodePathPart(name.slice(21));
return decodePathPart(name);
}
function hasProperties(t) {
return t && Object.keys(t).length > 0;
}
export function recurseSchema(t, convert) {
if (typeof t !== 'object')
return t;
const schema = t;
return {
...(schema),
...(typeof schema.items !== 'object' ? {}
: Array.isArray(schema.items)
? { items: schema.items.map(item => convert(item)) }
: { items: convert(schema.items) }),
...(typeof schema.additionalItems !== 'object' ? {}
: { additionalItems: convert(schema.additionalItems) }),
...(typeof schema.contains !== 'object' ? {}
: { contains: convert(schema.contains) }),
...(!hasProperties(schema.properties) ? {} :
{
properties: Object.fromEntries(Object.keys(schema.properties)
.map(key => [key, convert(schema.properties?.[key])])),
}),
...(!hasProperties(schema.patternProperties) ? {} :
{
patternProperties: Object.fromEntries(Object.keys(schema.patternProperties)
.map(key => [key, convert(schema.patternProperties?.[key])])),
}),
...(typeof schema.additionalProperties !== 'object' ? {}
: { additionalProperties: convert(schema.additionalProperties) }),
...(!hasProperties(schema.dependencies) ? {} :
{
dependencies: Object.fromEntries(Object.keys(schema.dependencies)
.map(key => [key, convert(schema.dependencies?.[key])])),
}),
...(typeof schema.propertyNames !== 'object' ? {}
: { propertyNames: convert(schema.propertyNames) }),
...(typeof schema.if !== 'object' ? {}
: { if: convert(schema.if) }),
...(typeof schema.then !== 'object' ? {}
: { then: convert(schema.then) }),
...(typeof schema.else !== 'object' ? {}
: { else: convert(schema.else) }),
...((typeof schema.allOf !== 'object' || !schema.allOf.length) ? {}
: { allOf: schema.allOf.map((item) => convert(item)) }),
...((typeof schema.anyOf !== 'object' || !schema.anyOf.length) ? {}
: { anyOf: schema.anyOf.map((item) => convert(item)) }),
...((typeof schema.oneOf !== 'object' || !schema.oneOf.length) ? {}
: { oneOf: schema.oneOf.map((item) => convert(item)) }),
...(typeof schema.not !== 'object' ? {}
: { not: convert(schema.not) }),
...(!hasProperties(schema.definitions) ? {} :
{
definitions: Object.fromEntries(Object.keys(schema.definitions)
.map(key => [key, convert(schema.definitions?.[key])])),
}),
};
}