|
1 |
| -const { buildNotification } = require("./../lib/utils"); |
| 1 | +const { buildNotification } = require("./../lib/utils") |
| 2 | +const cds = require('@sap/cds') |
2 | 3 |
|
3 |
| -const cds = require('@sap/cds'); |
4 |
| -const Base = cds.outboxed ? cds.Service : require('@sap/cds/libx/_runtime/messaging/Outbox'); |
| 4 | +class NotificationService extends cds.Service { |
5 | 5 |
|
6 |
| -module.exports = class NotificationService extends Base { |
7 |
| - notify (message) { |
8 |
| - // Subclasses simply register handlers for 'notification' events |
9 |
| - // App code could plugin own before / after handlers |
10 |
| - return this.emit('notification', buildNotification(message)) |
| 6 | + /** |
| 7 | + * Emits a notification. Method notify can be used alternatively. |
| 8 | + * @param {string} [event] - The notification type. |
| 9 | + * @param {object} message - The message object |
| 10 | + */ |
| 11 | + emit (event, message) { |
| 12 | + // Outbox calls us with a req object, e.g. { event, data, headers } |
| 13 | + if (event.event) return super.emit (event) |
| 14 | + // First argument is optional for convenience |
| 15 | + if (!message) [ message, event ] = [ event ] |
| 16 | + // CAP events translate to notification types and vice versa |
| 17 | + if (event) message.type = event |
| 18 | + else event = message.type || message.NotificationTypeKey || 'Default' |
| 19 | + // Prepare and emit the notification |
| 20 | + message = buildNotification(message) |
| 21 | + return super.emit (event, message) |
11 | 22 | }
|
| 23 | + |
| 24 | + /** |
| 25 | + * That's just a semantic alias for emit. |
| 26 | + */ |
| 27 | + notify (type, message) { |
| 28 | + return this.emit (type,message) |
| 29 | + } |
| 30 | + |
| 31 | +} |
| 32 | +module.exports = NotificationService |
| 33 | + |
| 34 | +// Without Generic Outbox only alert.notify() can be used, not alert.emit() |
| 35 | +// Remove that when @sap/cds with Generic Outbox is released |
| 36 | +if (!cds.outboxed) { |
| 37 | + class OutboxedNotificationService extends require('@sap/cds/libx/_runtime/messaging/Outbox') {} |
| 38 | + OutboxedNotificationService.prototype.notify = NotificationService.prototype.emit |
| 39 | + module.exports = OutboxedNotificationService |
12 | 40 | }
|
0 commit comments