@grouparoo/core
Version:
The Grouparoo Core
69 lines (68 loc) • 2.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Notifier = void 0;
const actionhero_1 = require("actionhero");
const Notification_1 = require("../models/Notification");
const sequelize_1 = require("sequelize");
class Notifier {
/**
* Generate the notification via `buildNotification` and store it
* Also check if there are any notifications to remove with `pruneNotifications`
*/
async run() {
(0, actionhero_1.log)(`running notifier: ${this.constructor.name}`);
const notificationPayload = await this.buildNotification();
if (!notificationPayload)
return;
await this.storeOrUpdateNotification(notificationPayload);
await this.pruneNotifications();
}
async storeOrUpdateNotification(notificationPayload) {
// the combination of `from` + `subject` is the unique key for the notification
let notification = await Notification_1.Notification.findOne({
where: {
from: this.from,
subject: notificationPayload.subject,
},
});
if (!notification) {
notification = await Notification_1.Notification.create({
from: this.from,
subject: notificationPayload.subject,
body: notificationPayload.body,
cta: notificationPayload.cta,
ctaLink: notificationPayload.ctaLink,
});
}
else {
// always update the message with new body content
await notification.update({
body: notificationPayload.body,
cta: notificationPayload.cta,
ctaLink: notificationPayload.ctaLink,
updatedAt: new Date(), // always bump the `updatedAt`
});
}
}
/**
* Remove all notifications from this notifier
*/
async clearNotifications() {
return Notification_1.Notification.destroy({
where: { from: this.from },
});
}
async pruneNotifications() {
const oldNotifications = await Notification_1.Notification.findAll({
where: { from: this.from },
offset: this.messageLimit,
order: [["createdAt", "desc"]],
});
if (oldNotifications.length === 0)
return;
await Notification_1.Notification.destroy({
where: { id: { [sequelize_1.Op.in]: oldNotifications.map((n) => n.id) } },
});
}
}
exports.Notifier = Notifier;