koas-swagger-ui
Version:
Koas Swagger UI serves Swagger UI. This requires the `specURL` variable to have been set on the `ctx.openApi` object. Typically this is done by combining it with [`koas-spec-handler`][].
94 lines (91 loc) • 2.89 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.swaggerUI = exports.SwaggerUIBundle = void 0;
require("koas-spec-handler");
const fs_1 = require("fs");
const path_1 = require("path");
const swagger_ui_dist_1 = require("swagger-ui-dist");
const plugins_1 = require("./plugins");
const presets_1 = require("./presets");
const utils_1 = require("./utils");
exports.SwaggerUIBundle = {
plugins: plugins_1.SwaggerUIBundlePlugin,
presets: presets_1.SwaggerUIBundlePreset,
};
const render = (title, url, presets, plugins) => `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>${title}</title>
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" />
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
<style>
html {
overflow-y: scroll;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 0;
background: #fafafa;
}
</style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="./swagger-ui-bundle.js"></script>
<script>
SwaggerUIBundle({
url: ${JSON.stringify(url)},
dom_id: '#swagger-ui',
deepLinking: true,
displayOperationId: true,
presets: [${presets.join(', ')}],
plugins: [${plugins.join(', ')}],
layout: 'BaseLayout',
});
</script>
</body>
</html>`;
const paths = [
'favicon-16x16.png',
'favicon-32x32.png',
'oauth2-redirect.html',
'swagger-ui-bundle.js',
'swagger-ui-bundle.js.map',
'swagger-ui.css',
'swagger-ui.css.map',
];
/**
* Serve Swagger UI for the Koas API.
*
* @param options - The options for Swagger UI.
* @returns Koas middleware that servers Swagger UI
*/
function swaggerUI({ plugins = [plugins_1.SwaggerUIBundlePlugin.DownloadUrl], presets = [presets_1.SwaggerUIBundlePreset.apis], url = '/', } = {}) {
const pathMap = new Map(paths.map((p) => [
(0, utils_1.relativeRequestPath)(url, p),
[(0, path_1.join)((0, swagger_ui_dist_1.absolutePath)(), p), (0, path_1.parse)(p).ext],
]));
return ({ document, runAlways }) => runAlways(async (ctx, next) => {
var _a;
const { specURL } = ctx.openApi;
if (ctx.path === url) {
ctx.body = render(((_a = document.info) === null || _a === void 0 ? void 0 : _a.title) || 'SwaggerUI', specURL, presets, plugins);
ctx.type = 'html';
return;
}
if (pathMap.has(ctx.path)) {
const [file, type] = pathMap.get(ctx.path);
ctx.body = await fs_1.promises.readFile(file);
ctx.type = type;
return;
}
return next();
});
}
exports.swaggerUI = swaggerUI;