UNPKG

@nestjs/swagger

Version:

OpenAPI for NestJS: generate the API document from controllers and decorators, serve Swagger UI, and derive request types with mapped types.

113 lines (112 loc) • 3.23 kB
const COMBINATOR_KEYS = ['allOf', 'oneOf', 'anyOf']; const EXCLUSIVE_BOUND_KEYS = [ ['exclusiveMinimum', 'minimum'], ['exclusiveMaximum', 'maximum'] ]; const DATA_KEYS = new Set(['example', 'examples', 'default', 'const', 'enum']); const NAME_KEYED_MAPS = new Set([ 'properties', 'patternProperties', '$defs', 'schemas', 'headers', 'responses', 'requestBodies', 'parameters', 'callbacks', 'pathItems', 'webhooks', 'encoding' ]); export function convertNullableToOas31(document) { walk(document); } function walk(node) { if (Array.isArray(node)) { node.forEach(walk); return; } if (!isObject(node)) { return; } for (const [key, value] of Object.entries(node)) { if (DATA_KEYS.has(key) || key.startsWith('x-')) { continue; } if (NAME_KEYED_MAPS.has(key) && isObject(value)) { for (const [name, entry] of Object.entries(value)) { if (key === 'responses' && name.startsWith('x-')) { continue; } walk(entry); } } else { walk(value); } } convertSchema(node); convertExclusiveBounds(node); } function convertSchema(schema) { if (typeof schema.nullable !== 'boolean') { return; } const isNullable = schema.nullable; delete schema.nullable; if (!isNullable) { return; } const combinator = COMBINATOR_KEYS.find((key) => Array.isArray(schema[key])); if ('$ref' in schema || combinator) { schema.anyOf = [extractInnerSchema(schema, combinator), { type: 'null' }]; return; } if (schema.type !== undefined) { const types = Array.isArray(schema.type) ? schema.type : [schema.type]; schema.type = types.includes('null') ? types : [...types, 'null']; } if (Array.isArray(schema.enum) && !schema.enum.includes(null)) { schema.enum = [...schema.enum, null]; } } function convertExclusiveBounds(schema) { for (const [exclusiveKey, boundKey] of EXCLUSIVE_BOUND_KEYS) { if (typeof schema[exclusiveKey] !== 'boolean') { continue; } if (schema[exclusiveKey] && typeof schema[boundKey] === 'number') { schema[exclusiveKey] = schema[boundKey]; delete schema[boundKey]; } else { delete schema[exclusiveKey]; } } } function extractInnerSchema(schema, combinator) { const inner = {}; if ('$ref' in schema) { inner.$ref = schema.$ref; delete schema.$ref; } if (combinator) { const members = schema[combinator]; delete schema[combinator]; if (schema.type === 'object' && !('properties' in schema)) { delete schema.type; } if (!('$ref' in inner) && combinator === 'allOf' && members.length === 1) { Object.assign(inner, members[0]); } else { inner[combinator] = members; } } return inner; } function isObject(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }