Implement db.event.del (delete)

This commit is contained in:
D. Berge
2020-08-22 20:26:03 +02:00
parent 517291d5c9
commit ba160c441c
2 changed files with 128 additions and 1 deletions

View File

@@ -0,0 +1,127 @@
const { setSurvey, transaction } = require('../connection');
async function deleteTimedEventLabel (label, eventId, client) {
const text = `
DELETE
FROM events_timed_labels
WHERE label = $1 AND id = $2;
`;
// console.log("deleteTimedEventLabel", label, eventId);
return await client.query(text, [label, eventId]);
}
async function deleteSeqLabel (label, eventId, client) {
const text = `
DELETE
FROM events_seq_labels
WHERE label = $1 AND id = $2;
`;
// console.log("deleteSeqLabel", label, eventId);
return await client.query(text, [label, eventId]);
}
async function deleteTimedEvent (eventId, client) {
const text = `
DELETE
FROM events_timed
WHERE id = $1;
`;
// console.log("deleteTimedEvent", eventId);
return await client.query(text, [eventId]);
}
async function deleteSeqEvent (eventId, client) {
const text = `
DELETE
FROM events_seq
WHERE id = $1;
`;
// console.log("deleteSeqEvent", eventId);
return await client.query(text, [eventId]);
}
/**
* Delete events from the database.
*
* Events may have the following forms:
*
* Delete event associated with a time:
*
* {
* type: "timed",
* id: …,
* }
*
* Delete the listed labels associated with a
* time event, but not the event itself.
*
* {
* type: "timed",
* id: …,
* labels: [ "…", "…", … ]
* }
*
* Delete event associated with a shotpoint:
*
* {
* type: "sequence",
* id: …,
* }
*
* Delete only the labels, not the event itself:
*
* {
* type: "sequence",
* id: …,
* labels: [ "…", "…", … ]
* }
*
*/
async function del (projectId, payload, opts = {}) {
// console.log("delete event", projectId, payload);
const client = await setSurvey(projectId);
await transaction.begin(client);
try {
if (!Array.isArray(payload)) {
payload = [payload];
}
// console.log("Payload", payload);
for (const event of payload) {
// console.log("Event", event);
if (event.type && event.id) {
const eventId = event.id;
if (event.labels) {
const handler = event.type == "timed"
? deleteTimedEventLabel
: deleteSeqLabel;
for (const label of event.labels) {
await handler(label, eventId, client);
}
} else {
if (event.type == "timed") {
await deleteTimedEvent(eventId, client);
} else {
await deleteSeqEvent(eventId, client);
}
}
} else {
throw { status: 400, message: "Unrecognised event kind" };
}
}
transaction.commit(client);
} catch (err) {
transaction.rollback(client)
} finally {
client.release();
}
}
module.exports = del;

View File

@@ -4,5 +4,5 @@ module.exports = {
get: require('./get'),
post: require('./post'),
put: require('./put'),
delete: require('./delete')
del: require('./delete')
}