Files
dougal-software/lib/www/server/lib/db/info/put.js
D. Berge f10103d396 Enfore info key access restrictions on the API.
Obviously, those keys can be edited freely at the database
level. This is intended.
2022-02-06 22:40:53 +01:00

44 lines
1.1 KiB
JavaScript

const { setSurvey, transaction } = require('../connection');
const checkPermission = require('./check-permission');
async function put (projectId, path, payload, opts = {}, role) {
const client = await setSurvey(projectId);
const [key, ...jsonpath] = (path||"").split("/").filter(i => i.length);
if (!checkPermission(key, "put", role)) {
throw {status: 403, message: "Forbidden"};
return;
}
try {
const text = jsonpath.length
? `
INSERT INTO info (key, value)
VALUES ($2, jsonb_set('${isNaN(Number(jsonpath[0])) ? "{}" : "[]"}'::jsonb, $3, $1))
ON CONFLICT (key) DO UPDATE
SET
key = $2,
value = jsonb_set((SELECT value FROM info WHERE key = $2), $3, $1)
RETURNING *;
`
: `
INSERT INTO info (key, value)
VALUES ($2, $1)
ON CONFLICT (key) DO UPDATE
SET
key = $2,
value = $1
RETURNING *;
`;
const values = jsonpath.length ? [JSON.stringify(payload), key, jsonpath] : [JSON.stringify(payload), key];
await client.query(text, values);
} catch (err) {
console.error("ERROR", err);
throw err;
} finally {
client.release();
}
}
module.exports = put;