Files
dougal-software/lib/www/server/api/middleware/openapi/get.js
D. Berge 3c4a558e02 Serve OpenAPI document on API root.
When a client makes a request for `/` (the root of
the API), the OpenAPI description is served in an
appropriate format according to the `Accept` request
header, as follows:

Accept: text/html => HTML version
Accept: application/json => JSON version
Accept: * => YAML version
2020-12-29 16:20:57 +01:00

45 lines
1.1 KiB
JavaScript

const fs = require('fs');
const path = require('path');
const YAML = require('yaml');
const openapiYAML = path.join(__dirname, "../../../spec/openapi.yaml");
const openapiHTML = path.join(__dirname, "../../../spec/openapi.html");
module.exports = async function (req, res, next) {
function handleError (err) {
if (err instanceof TypeError || err.code == "ENOENT") {
res.status(404).send();
next();
} else {
next(err);
}
}
try {
if (req.accepts("text/html")) {
const stream = fs.createReadStream(openapiHTML);
stream.on('open', () => {
res.set("Content-Type", "text/html");
stream.pipe(res);
});
stream.on('end', next);
stream.on('error', handleError);
} else if (req.accepts("application/json")) {
const text = await fs.promises.readFile(openapiYAML, 'utf8');
res.json(YAML.parse(text));
next();
} else {
const stream = fs.createReadStream(openapiYAML);
stream.on('open', () => {
res.set("Content-Type", "application/yaml");
stream.pipe(res);
});
stream.on('end', next);
stream.on('error', handleError);
}
} catch (err) {
handleError(err);
}
};