@nestjs/swagger
Version:
OpenAPI for NestJS: generate the API document from controllers and decorators, serve Swagger UI, and derive request types with mapped types.
33 lines (32 loc) • 950 B
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)}]`;
}
}
export function buildJSInitOptions(initOptions) {
const fns = [];
const placeholders = [];
let json = JSON.stringify(initOptions, (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};`;
}