mirror of
https://gitlab.com/wgp/dougal/software.git
synced 2025-12-06 10:47:07 +00:00
Implement info.put() database method.
Replaces an existing element with a new one, or inserts it if there is nothing to replace. The element may be deeply nested inside a JSON object or array in the `info` table. Works for both public.info and survey_?.info.
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
const { setSurvey, transaction } = require('../connection');
|
||||
|
||||
async function put (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_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;
|
||||
|
||||
Reference in New Issue
Block a user