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.

74 lines (73 loc) • 3.37 kB
import { isFunction, isString } from '@nestjs/common/utils/shared.utils.js'; import pick from 'es-toolkit/compat/pick'; import 'reflect-metadata'; import { DECORATORS } from '../constants.js'; import { createApiPropertyDecorator } from '../decorators/api-property.decorator.js'; import { METADATA_FACTORY_NAME } from '../plugin/plugin-constants.js'; export class ModelPropertiesAccessor { getModelProperties(prototype) { const properties = Reflect.getMetadata(DECORATORS.API_MODEL_PROPERTIES_ARRAY, prototype) || []; return properties .filter(isString) .filter((key) => key.charAt(0) === ':' && !isFunction(prototype[key])) .map((key) => key.slice(1)) .filter((key) => !this.isHiddenProperty(prototype, key)); } isHiddenProperty(prototype, key, stopAt) { let current = prototype; while (current && current !== Object.prototype) { if (Reflect.getOwnMetadata(DECORATORS.API_MODEL_PROPERTY_HIDDEN, current, key)) { return true; } if (current === stopAt || Reflect.getOwnMetadata(DECORATORS.API_MODEL_PROPERTIES, current, key)) { return false; } current = Reflect.getPrototypeOf(current); } return false; } keepDecoratedInheritedOptions(prototype, key) { if (Reflect.hasOwnMetadata(DECORATORS.API_MODEL_PROPERTIES, prototype, key)) { return; } const inheritedMetadata = Reflect.getMetadata(DECORATORS.API_MODEL_PROPERTIES, prototype, key); if (!inheritedMetadata) { return; } const decoratedOptions = new Set(); for (let current = Reflect.getPrototypeOf(prototype); current && current !== Object.prototype; current = Reflect.getPrototypeOf(current)) { (Reflect.getOwnMetadata(DECORATORS.API_MODEL_PROPERTY_EXPLICIT_OPTIONS, current, key) ?? []).forEach((option) => decoratedOptions.add(option)); } decoratedOptions.delete('type'); decoratedOptions.delete('isArray'); Reflect.defineMetadata(DECORATORS.API_MODEL_PROPERTIES, pick(inheritedMetadata, [...decoratedOptions]), prototype, key); } applyMetadataFactory(prototype) { const classPrototype = prototype; do { if (!prototype.constructor) { return; } if (!prototype.constructor[METADATA_FACTORY_NAME]) { continue; } const metadata = prototype.constructor[METADATA_FACTORY_NAME](); const properties = Object.keys(metadata); const isOwnFactory = prototype === classPrototype && Object.prototype.hasOwnProperty.call(prototype.constructor, METADATA_FACTORY_NAME); properties.forEach((key) => { if (this.isHiddenProperty(classPrototype, key, prototype)) { return; } if (isOwnFactory) { this.keepDecoratedInheritedOptions(classPrototype, key); } createApiPropertyDecorator(metadata[key], false)(classPrototype, key); }); } while ((prototype = Reflect.getPrototypeOf(prototype)) && prototype !== Object.prototype && prototype); } }