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.

76 lines (75 loc) • 2.69 kB
import { DECORATORS } from '../constants.js'; import { createLazyEnum, getEnumType, getEnumValues } from '../utils/enum.utils.js'; import { createPropertyDecorator, getTypeIsArrayTuple } from './helpers.js'; const isEnumArray = (opts) => opts.isArray && 'enum' in opts && opts.enum !== undefined; export function ApiProperty(options = {}) { return createApiPropertyDecorator(options); } export function createApiPropertyDecorator(options = {}, overrideExisting = true) { const [type, isArray] = getTypeIsArrayTuple(options.type, options.isArray); options = { ...options, type, isArray }; if (typeof options.enum === 'function') { options.enum = createLazyEnum(options.enum, !options.type); } else if (isEnumArray(options)) { options.type = 'array'; const enumValues = getEnumValues(options.enum); options.items = { type: getEnumType(enumValues), enum: enumValues }; delete options.enum; } else if ('enum' in options && options.enum !== undefined) { const enumValues = getEnumValues(options.enum); options.enum = enumValues; if (!options.type) { options.type = getEnumType(enumValues); } } if (Array.isArray(options.type)) { const innerType = options.type[0]; options.type = 'array'; options.items = { type: 'array', items: { type: typeof innerType === 'function' ? innerType.name.charAt(0).toLowerCase() + innerType.name.slice(1) : innerType } }; } if (options.pattern instanceof RegExp) { options.pattern = options.pattern.source; } const decorator = createPropertyDecorator(DECORATORS.API_MODEL_PROPERTIES, options, overrideExisting); if (!overrideExisting) { return decorator; } const explicitOptions = Object.keys(options).filter((option) => options[option] !== undefined); return (target, propertyKey) => { decorator(target, propertyKey); Reflect.defineMetadata(DECORATORS.API_MODEL_PROPERTY_EXPLICIT_OPTIONS, [ ...new Set([ ...(Reflect.getOwnMetadata(DECORATORS.API_MODEL_PROPERTY_EXPLICIT_OPTIONS, target, propertyKey) ?? []), ...explicitOptions ]) ], target, propertyKey); }; } export function ApiPropertyOptional(options = {}) { return ApiProperty({ ...options, required: false }); } export function ApiResponseProperty(options = {}) { return ApiProperty({ readOnly: true, ...options }); }