-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathNotificationBroker.ts
77 lines (73 loc) · 2.93 KB
/
NotificationBroker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { DeliveryInformation } from '@dm3-org/dm3-lib-messaging';
import { Email } from '../channels/Email';
import {
INotificationBroker,
GetNotificationChannels,
NotificationChannel,
NotificationChannelType,
INotificationChannel,
NotificationType,
} from '../types';
/**
* Sets up the notification broker with supported notification channels.
* Separated from the NotificationBroker function to make it testable.
* @param {INotificationChannel[]} supportedChannels - List of supported notification channels by the deliveryService.
* @returns {INotificationBroker} Object with a method to send notifications.
*/
export const _setupNotficationBroker = (
supportedChannels: INotificationChannel[],
): INotificationBroker => {
async function sendNotification(
deliveryInformation: DeliveryInformation,
getNotificationChannels: GetNotificationChannels,
) {
//Get users notification channels from DB
const usersNotificationChannels = await getNotificationChannels(
deliveryInformation.to,
);
await Promise.all(
usersNotificationChannels.map(async (channel) => {
const deliveryServiceNotificationChannel =
supportedChannels.find((c) => c.type === channel.type);
//User specified a channel that is not supported.
//This should be prevented by refusing any schema that allows to provide a channel that is not supported
if (!deliveryServiceNotificationChannel) {
throw new Error(
`Channel type ${channel.type} is not supported`,
);
}
return await deliveryServiceNotificationChannel.send(
channel.config,
deliveryInformation,
);
}),
);
}
return { sendNotification };
};
/**
* Creates a notification broker based on the provided notification channels.
* @param {DeliveryServiceProperties} options - Delivery service properties including notification channels.
* @returns {INotificationBroker} An instance of the notification broker.
* @throws {Error} If an unsupported channel type is encountered.
*/
export const NotificationBroker = (
notificationChannel: NotificationChannel[],
notificationType: NotificationType,
): INotificationBroker => {
const channels = notificationChannel.map((channel) => {
switch (channel.type) {
case NotificationChannelType.EMAIL:
channel.config.notificationType = notificationType;
return {
type: NotificationChannelType.EMAIL,
send: Email(channel.config).send,
};
default:
throw new Error(
`Channel type ${channel.type} is not supported`,
);
}
});
return _setupNotficationBroker(channels);
};