mirror of
https://gitlab.com/wgp/dougal/software.git
synced 2025-12-06 12:17:08 +00:00
Implement info.post() database method.
It adds an element to a JSON array corresponding to a key in the info table. Errors out if the value is not an array.
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
const { setSurvey, transaction } = require('../connection');
|
||||
|
||||
async function post (projectId, path, payload, opts = {}) {
|
||||
const client = await setSurvey(projectId);
|
||||
const [key, ...jsonpath] = (path||"").split("/").filter(i => i.length);
|
||||
|
||||
try {
|
||||
const text = jsonpath.length
|
||||
? `
|
||||
INSERT INTO info (key, value)
|
||||
VALUES ($2, jsonb_insert('${isNaN(Number(jsonpath[0])) ? "{}" : "[]"}'::jsonb, $3, $1))
|
||||
ON CONFLICT (key) DO UPDATE
|
||||
SET
|
||||
key = $2,
|
||||
value = jsonb_insert((SELECT value FROM info WHERE key = $2), $3, $1, true)
|
||||
RETURNING *;
|
||||
`
|
||||
: `
|
||||
INSERT INTO info (key, value)
|
||||
VALUES ($2, jsonb_insert('[]'::jsonb, '{0}', $1))
|
||||
ON CONFLICT (key) DO UPDATE
|
||||
SET
|
||||
key = $2,
|
||||
value = jsonb_insert((SELECT value FROM info WHERE key = $2), '{-1}'::text[], $1, true)
|
||||
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);
|
||||
if (err.code == 22023) {
|
||||
throw {status: 400, message: "Cannot post to non-array"};
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = post;
|
||||
|
||||
Reference in New Issue
Block a user