2021-04-04 19:52:19 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const knex = require('./knex');
|
2021-04-04 20:52:54 +00:00
|
|
|
const { HttpError } = require('./errors');
|
2021-04-04 19:52:19 +00:00
|
|
|
|
2021-04-04 20:52:54 +00:00
|
|
|
async function addAlert(alert, sessionUser) {
|
|
|
|
if (!sessionUser) {
|
|
|
|
throw new HttpError('You are not authenthicated', 401);
|
|
|
|
}
|
2021-04-04 19:52:19 +00:00
|
|
|
|
2021-04-04 20:52:54 +00:00
|
|
|
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;
|
2021-04-04 19:52:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function removeAlert(alertId) {
|
|
|
|
await knex('alerts').where('id', alertId).delete();
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
addAlert,
|
|
|
|
removeAlert,
|
|
|
|
};
|