From 025f3f774d31d976a4d1c1ebe0bf600ba65ca698 Mon Sep 17 00:00:00 2001 From: "D. Berge" Date: Mon, 23 Oct 2023 19:22:50 +0200 Subject: [PATCH] Add YAML and CSV support to project configuration GET endpoint --- .../middleware/project/configuration/get.js | 60 +++++++++++++++++-- 1 file changed, 54 insertions(+), 6 deletions(-) diff --git a/lib/www/server/api/middleware/project/configuration/get.js b/lib/www/server/api/middleware/project/configuration/get.js index 7903887..498aff5 100644 --- a/lib/www/server/api/middleware/project/configuration/get.js +++ b/lib/www/server/api/middleware/project/configuration/get.js @@ -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); } - -}; +}