@nestjs/swagger
Version:
OpenAPI for NestJS: generate the API document from controllers and decorators, serve Swagger UI, and derive request types with mapped types.
53 lines (52 loc) • 2.31 kB
JavaScript
import isFunction from 'es-toolkit/compat/isFunction';
import { DECORATORS } from '../constants.js';
import { getSchemaPath } from '../utils/index.js';
import { isBuiltInType } from '../utils/is-built-in-type.util.js';
const mapCallbacksToSwaggerCallbacks = (callbacksData, schemas, schemaObjectFactory) => {
return callbacksData.reduce((acc, callbackData) => {
const { name: eventName, callbackUrl, method: callbackMethod, requestBody, expectedResponse } = callbackData;
if (isFunction(requestBody.type) && !isBuiltInType(requestBody.type)) {
schemaObjectFactory.exploreModelSchema(requestBody.type, schemas);
}
return {
...acc,
[eventName]: {
[callbackUrl]: {
[callbackMethod]: {
requestBody: {
required: true,
content: {
'application/json': {
schema: {
$ref: getSchemaPath(requestBody.type)
}
}
}
},
responses: {
[expectedResponse.status]: {
description: expectedResponse.description ||
'Your server returns this code if it accepts the callback'
}
}
}
}
}
};
}, {});
};
export const exploreGlobalApiCallbacksMetadata = (schemas, schemaObjectFactory, metatype) => {
const callbacksData = Reflect.getMetadata(DECORATORS.API_CALLBACKS, metatype);
if (!callbacksData) {
return undefined;
}
return {
callbacks: mapCallbacksToSwaggerCallbacks(callbacksData, schemas, schemaObjectFactory)
};
};
export const exploreApiCallbacksMetadata = (schemas, schemaObjectFactory, instance, prototype, method) => {
const callbacksData = Reflect.getMetadata(DECORATORS.API_CALLBACKS, method);
if (!callbacksData)
return callbacksData;
return mapCallbacksToSwaggerCallbacks(callbacksData, schemas, schemaObjectFactory);
};