@nestjs/swagger
Version:
OpenAPI for NestJS: generate the API document from controllers and decorators, serve Swagger UI, and derive request types with mapped types.
67 lines (66 loc) • 2.93 kB
JavaScript
import identity from 'es-toolkit/compat/identity';
import omitBy from 'es-toolkit/compat/omitBy';
import { DECORATORS } from '../constants.js';
import { METADATA_FACTORY_NAME } from '../plugin/plugin-constants.js';
import { ModelPropertiesAccessor } from '../services/model-properties-accessor.js';
const modelPropertiesAccessor = new ModelPropertiesAccessor();
function capitalizeFirstLetter(value) {
return value.charAt(0).toUpperCase() + value.slice(1);
}
function sanitizeTypeNameSegment(value) {
return String(value).replace(/[^A-Za-z0-9_$]/g, '_');
}
export function setMappedTypeClassName(target, prefix, classRef, keys = []) {
Object.defineProperty(target, 'name', {
configurable: true,
get: () => {
const parentTypeName = classRef.name || 'Anonymous';
const documentedKeys = new Set(modelPropertiesAccessor.getModelProperties(classRef.prototype));
const mappedProperties = keys
.filter((key) => documentedKeys.has(String(key)))
.map((key) => capitalizeFirstLetter(sanitizeTypeNameSegment(key)))
.join('');
return `${prefix}${parentTypeName}${mappedProperties}`;
}
});
}
export function clonePluginMetadataFactory(target, parent, transformFn = identity) {
let targetMetadata = {};
const classPrototype = parent;
do {
if (!parent.constructor) {
return;
}
if (!parent.constructor[METADATA_FACTORY_NAME]) {
continue;
}
const parentMetadata = omitBy(parent.constructor[METADATA_FACTORY_NAME](), (_value, key) => modelPropertiesAccessor.isHiddenProperty(classPrototype, key, parent));
targetMetadata = {
...parentMetadata,
...targetMetadata
};
} while ((parent = Reflect.getPrototypeOf(parent)) &&
parent !== Object.prototype &&
parent);
targetMetadata = transformFn(targetMetadata);
if (target[METADATA_FACTORY_NAME]) {
const originalFactory = target[METADATA_FACTORY_NAME];
target[METADATA_FACTORY_NAME] = () => {
const originalMetadata = originalFactory();
return {
...originalMetadata,
...targetMetadata
};
};
}
else {
target[METADATA_FACTORY_NAME] = () => targetMetadata;
}
}
export function inheritExplicitApiPropertyOptions(source, target, propertyKey, extraOptions = []) {
const explicitOptions = new Set(extraOptions);
for (let current = source; current && current !== Object.prototype; current = Reflect.getPrototypeOf(current)) {
(Reflect.getOwnMetadata(DECORATORS.API_MODEL_PROPERTY_EXPLICIT_OPTIONS, current, propertyKey) ?? []).forEach((option) => explicitOptions.add(option));
}
Reflect.defineMetadata(DECORATORS.API_MODEL_PROPERTY_EXPLICIT_OPTIONS, [...explicitOptions], target, propertyKey);
}