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
This commit is contained in:
D. Berge
2020-12-29 16:20:57 +01:00
parent 76001cffe1
commit 3c4a558e02
4 changed files with 53 additions and 1 deletions

View File

@@ -71,6 +71,9 @@ app.map({
'/logout': { '/logout': {
get: [ mw.user.logout ], get: [ mw.user.logout ],
post: [ mw.user.logout ] post: [ mw.user.logout ]
},
'/': {
get: [ mw.openapi.get ]
} }
}); });

View File

@@ -11,5 +11,6 @@ module.exports = {
navdata: require('./navdata'), navdata: require('./navdata'),
configuration: require('./configuration'), configuration: require('./configuration'),
info: require('./info'), info: require('./info'),
meta: require('./meta') meta: require('./meta'),
openapi: require('./openapi')
}; };

View File

@@ -0,0 +1,44 @@
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);
}
};

View File

@@ -0,0 +1,4 @@
module.exports = {
get: require('./get')
}