@nestjs/swagger
Version:
OpenAPI for NestJS: generate the API document from controllers and decorators, serve Swagger UI, and derive request types with mapped types.
41 lines (40 loc) • 1.19 kB
JavaScript
import { randomUUID } from 'crypto';
import { Script } from 'vm';
function serializeFunction(fn) {
const source = fn.toString();
try {
new Script(`(${source})`);
return source;
}
catch (err) {
if (!(err instanceof SyntaxError)) {
return source;
}
return `({ ${source} })[${JSON.stringify(fn.name)}]`;
}
}
function toPlainJSON(value) {
const json = JSON.stringify(value);
return json === undefined ? undefined : JSON.parse(json);
}
export function buildJSInitOptions(initOptions) {
const fns = [];
const placeholders = [];
const options = {
...initOptions,
swaggerDoc: toPlainJSON(initOptions.swaggerDoc)
};
let json = JSON.stringify(options, (key, value) => {
if (typeof value === 'function') {
const placeholder = randomUUID();
fns.push(value);
placeholders.push(placeholder);
return placeholder;
}
return value;
}, 2);
placeholders.forEach((placeholder, i) => {
json = json.replace(`"${placeholder}"`, () => serializeFunction(fns[i]));
});
return `let options = ${json};`;
}