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:
D. Berge
2021-05-20 18:14:43 +02:00
parent 6feb7d49ee
commit 1d38f6526b

View File

@@ -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;