doc-it-up
Version:
Generates automatic documentation for your code. Supports Express, Fastify, Koa, Hono, Elysia, and Hapi.
68 lines (65 loc) • 2.19 kB
JavaScript
import { _ as __awaiter } from '../chunks/tslib.es6-WQS2tr1v.js';
import { initDocsDirectory, DocItUpCore } from '../core.js';
import 'fs/promises';
import 'path';
const expressMiddleware = (options = {}) => {
if (options.docsDir)
initDocsDirectory(options.docsDir);
else
initDocsDirectory();
return (req, res, next) => {
if (req.path.startsWith('/docs'))
return next();
const originalSend = res.send;
const originalJson = res.json;
let responseBody = null;
// Hook .json()
res.json = function (data) {
responseBody = data;
return originalJson.call(this, data);
};
// Hook .send()
res.send = function (data) {
if (!responseBody) {
try {
responseBody = typeof data === 'string' ? JSON.parse(data) : data;
}
catch (_a) {
responseBody = data;
}
}
return originalSend.call(this, data);
};
res.on('finish', () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
DocItUpCore.recordRequest({
method: req.method,
path: req.baseUrl ? req.baseUrl + req.path : req.path,
headers: req.headers,
query: req.query,
body: req.body,
params: req.params,
files: req.files
}, {
statusCode: res.statusCode,
statusMessage: res.statusMessage,
headers: res.getHeaders(),
body: responseBody
});
}
});
next();
};
};
const expressHandler = () => {
return (req, res) => __awaiter(void 0, void 0, void 0, function* () {
yield DocItUpCore.loadSpecs();
if (req.path.endsWith('/swagger.json')) {
res.json(DocItUpCore.getSwaggerSpec());
}
else {
res.send(DocItUpCore.getHtml());
}
});
};
export { expressHandler, expressMiddleware };