diff --git a/srv/notifyToConsole.js b/srv/notifyToConsole.js index 5c3e3bb..e8d11b5 100644 --- a/srv/notifyToConsole.js +++ b/srv/notifyToConsole.js @@ -5,7 +5,8 @@ const LOG = cds.log('notifications'); module.exports = class NotifyToConsole extends NotificationService { async init() { - this.on("notification", req => { + this.on("*", req => { + LOG._debug && LOG.debug('Handling notification event:', req.event) const notification = req.data; if (!notification) return console.log ( '\n---------------------------------------------------------------\n' + diff --git a/srv/notifyToRest.js b/srv/notifyToRest.js index 9a8f907..dcc5394 100644 --- a/srv/notifyToRest.js +++ b/srv/notifyToRest.js @@ -9,7 +9,7 @@ const NOTIFICATIONS_API_ENDPOINT = "v2/Notification.svc"; module.exports = exports = class NotifyToRest extends NotificationService { async init() { - this.on("notification", req => this.postNotification(req.data)) + this.on("*", req => this.postNotification(req.data)) return super.init() } diff --git a/srv/service.js b/srv/service.js index da1c8dd..3b230a6 100644 --- a/srv/service.js +++ b/srv/service.js @@ -1,12 +1,40 @@ -const { buildNotification } = require("./../lib/utils"); +const { buildNotification } = require("./../lib/utils") +const cds = require('@sap/cds') -const cds = require('@sap/cds'); -const Base = cds.outboxed ? cds.Service : require('@sap/cds/libx/_runtime/messaging/Outbox'); +class NotificationService extends cds.Service { -module.exports = class NotificationService extends Base { - notify (message) { - // Subclasses simply register handlers for 'notification' events - // App code could plugin own before / after handlers - return this.emit('notification', buildNotification(message)) + /** + * Emits a notification. Method notify can be used alternatively. + * @param {string} [event] - The notification type. + * @param {object} message - The message object + */ + emit (event, message) { + // Outbox calls us with a req object, e.g. { event, data, headers } + if (event.event) return super.emit (event) + // First argument is optional for convenience + if (!message) [ message, event ] = [ event ] + // CAP events translate to notification types and vice versa + if (event) message.type = event + else event = message.type || message.NotificationTypeKey || 'Default' + // Prepare and emit the notification + message = buildNotification(message) + return super.emit (event, message) } + + /** + * That's just a semantic alias for emit. + */ + notify (type, message) { + return this.emit (type,message) + } + +} +module.exports = NotificationService + +// Without Generic Outbox only alert.notify() can be used, not alert.emit() +// Remove that when @sap/cds with Generic Outbox is released +if (!cds.outboxed) { + class OutboxedNotificationService extends require('@sap/cds/libx/_runtime/messaging/Outbox') {} + OutboxedNotificationService.prototype.notify = NotificationService.prototype.emit + module.exports = OutboxedNotificationService }