Add YAML and CSV support to project configuration GET endpoint

This commit is contained in:
D. Berge
2023-10-23 19:22:50 +02:00
parent f26e746c2b
commit 025f3f774d

View File

@@ -1,13 +1,61 @@
const YAML = require('yaml');
const { stringify } = require('csv-stringify/sync');
const { project } = require('../../../../lib/db');
const { flatEntries } = require('../../../../lib/utils/flatEntries');
function json (req, res, next) {
if (res.locals.payload) {
res.status(200).send(res.locals.payload);
} else {
res.status(404).send({message: "Not found"});
}
next();
}
function yaml (req, res, next) {
if (res.locals.payload) {
res.status(200).send(YAML.stringify(res.locals.payload));
} else {
res.status(404).send({message: "Not found"});
}
next();
}
function csv (req, res, next) {
if (res.locals.payload) {
const fields = [ "key", "value" ];
const delimiter = req.query.delimiter ?? ",";
const text = stringify([fields, ...flatEntries(res.locals.payload)], {delimiter});
res.status(200).send(text);
} else {
res.status(404).send({message: "Not found"});
}
next();
}
module.exports = async function (req, res, next) {
try {
res.status(200).send(await project.configuration.get(req.params.project));
next();
const handlers = {
"application/json": json,
"application/yaml": yaml,
"text/csv": csv
};
const mimetype = (handlers[req.query.mime] && req.query.mime) || req.accepts(Object.keys(handlers));
if (mimetype) {
res.locals.payload = await project.configuration.get(req.params.project);
res.set("Content-Type", mimetype);
await handlers[mimetype](req, res, next);
} else {
res.status(406).send();
next();
}
} catch (err) {
next(err);
}
};
}