traxxx/src/alerts.js

56 lines
1.2 KiB
JavaScript
Raw Normal View History

'use strict';
const knex = require('./knex');
const { HttpError } = require('./errors');
async function addAlert(alert, sessionUser) {
if (!sessionUser) {
throw new HttpError('You are not authenthicated', 401);
}
if (!alert.actors?.length > 0 && !alert.tags?.length > 0 && !alert.entity) {
throw new HttpError('Alert must contain at least one actor, tag or entity', 400);
}
const [alertId] = await knex('alerts')
.insert({
user_id: sessionUser.id,
notify: alert.notify,
email: alert.email,
})
.returning('id');
await Promise.all([
alert.actors?.length > 0 && knex('alerts_actors')
.insert(alert.actors.map(actorId => ({
alert_id: alertId,
actor_id: actorId,
}))),
alert.tags?.length > 0 && knex('alerts_tags')
.insert(alert.tags.map(tagId => ({
alert_id: alertId,
tag_id: tagId,
}))),
alert.stashes?.length > 0 && knex('alerts_stashes')
.insert(alert.stashes.map(stashId => ({
alert_id: alertId,
stash_id: stashId,
}))),
alert.entity && knex('alerts_entities').insert({
alert_id: alertId,
entity_id: alert.entity,
}),
]);
return alertId;
}
async function removeAlert(alertId) {
await knex('alerts').where('id', alertId).delete();
}
module.exports = {
addAlert,
removeAlert,
};