Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const openapi = new OpenAPIBuilder({
info,
servers: [{ url: ServiceEndpoint }],
routes,
});
// create static files directory if not exists
const outputPath = SwaggerUIBucketName ?
path.join(__dirname, '..', '.serverless-static') : path.join(__dirname, '..', 'static');
fs.existsSync(outputPath) || fs.mkdirSync(outputPath);
// generate swagger.json
const apispec = openapi.getDefinition(routes, ServiceEndpoint);
// validate openapi and warn in case there are issues
const { valid, errors } = validate(apispec, 3);
if (valid) {
console.info('\x1b[32m[success]\x1b[0m Document is valid OpenAPI v3!');
} else {
console.warn(`\x1b[33m[warning]\x1b[0m Document is not valid OpenAPI!\n ${errors.length} validation errors:\n` +
JSON.stringify(errors, null, 2));
}
// write to swagger.json file under static/
const swaggerFile = path.join(outputPath, 'swagger.json');
fs.writeFileSync(swaggerFile, JSON.stringify(apispec));
console.info(`[info] Wrote OpenAPI spec to ${path.basename(outputPath)}/${path.basename(swaggerFile)}`);
// copy swagger ui dist files
const swaggerDist = getAbsoluteFSPath();
const swaggerFiles = fs.readdirSync(swaggerDist)
.filter(file => !file.endsWith('.map'));
toBeValidOpenAPI(received: any, version: number = 3) {
const { valid, errors } = validate(received, version);
return valid ? {
pass: true,
message: () => `Document is valid openapi v${version}`,
} : {
pass: false,
message: () => `Document is not valid openapi v${version}, ${errors.length} validation errors:\n` +
JSON.stringify(errors, null, 2),
};
},
});
public validateDefinition() {
const { valid, errors } = validateOpenAPI(this.document, 3);
if (!valid) {
const prettyErrors = JSON.stringify(errors, null, 2);
throw new Error(`Document is not valid OpenAPI. ${errors.length} validation errors:\n${prettyErrors}`);
}
return this.document;
}
public validateDefinition = () => {
const { valid, errors } = validateOpenAPI(this.document, 3);
if (!valid) {
const prettyErrors = JSON.stringify(errors, null, 2);
throw new Error(`Document is not valid OpenAPI. ${errors.length} validation errors:\n${prettyErrors}`);
}
return this.document;
};