-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathindex.ts
More file actions
246 lines (221 loc) · 8.1 KB
/
index.ts
File metadata and controls
246 lines (221 loc) · 8.1 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/**
* Copyright 2020, 2022, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { LogHandler, ErrorHandler } from '../../modules/logging';
import { objectValues } from '../../utils/fns';
import { ListenerPayload, NotificationListener, NotificationPayloadMap } from '../../shared_types';
import {
LOG_LEVEL,
LOG_MESSAGES,
NOTIFICATION_TYPES,
} from '../../utils/enums';
const MODULE_NAME = 'NOTIFICATION_CENTER';
interface NotificationCenterOptions {
logger: LogHandler;
errorHandler: ErrorHandler;
}
interface ListenerEntry {
id: number;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
callback: (notificationData: any) => void;
}
type NotificationListeners = {
[key: string]: ListenerEntry[];
}
/**
* NotificationCenter allows registration and triggering of callback functions using
* notification event types defined in NOTIFICATION_TYPES of utils/enums/index.js:
* - ACTIVATE: An impression event will be sent to Optimizely.
* - TRACK a conversion event will be sent to Optimizely
*/
export class NotificationCenter {
private logger: LogHandler;
private errorHandler: ErrorHandler;
private notificationListeners: NotificationListeners;
private listenerId: number;
/**
* @constructor
* @param {NotificationCenterOptions} options
* @param {LogHandler} options.logger An instance of a logger to log messages with
* @param {ErrorHandler} options.errorHandler An instance of errorHandler to handle any unexpected error
*/
constructor(options: NotificationCenterOptions) {
this.logger = options.logger;
this.errorHandler = options.errorHandler;
this.notificationListeners = {};
objectValues(NOTIFICATION_TYPES).forEach(
(notificationTypeEnum) => {
this.notificationListeners[notificationTypeEnum] = [];
}
);
this.listenerId = 1;
}
/**
* Add a notification callback to the notification center
* @param {string} notificationType One of the values from NOTIFICATION_TYPES in utils/enums/index.js
* @param {NotificationListener<T>} callback Function that will be called when the event is triggered
* @returns {number} If the callback was successfully added, returns a listener ID which can be used
* to remove the callback by calling removeNotificationListener. The ID is a number greater than 0.
* If there was an error and the listener was not added, addNotificationListener returns -1. This
* can happen if the first argument is not a valid notification type, or if the same callback
* function was already added as a listener by a prior call to this function.
*/
addNotificationListener<T extends ListenerPayload>(
notificationType: string,
callback: NotificationListener<T>
): number {
try {
const notificationTypeValues: string[] = objectValues(NOTIFICATION_TYPES);
const isNotificationTypeValid = notificationTypeValues.indexOf(notificationType) > -1;
if (!isNotificationTypeValid) {
return -1;
}
if (!this.notificationListeners[notificationType]) {
this.notificationListeners[notificationType] = [];
}
let callbackAlreadyAdded = false;
(this.notificationListeners[notificationType] || []).forEach(
(listenerEntry) => {
if (listenerEntry.callback === callback) {
callbackAlreadyAdded = true;
return;
}
});
if (callbackAlreadyAdded) {
return -1;
}
this.notificationListeners[notificationType].push({
id: this.listenerId,
callback: callback,
});
const returnId = this.listenerId;
this.listenerId += 1;
return returnId;
} catch (e: any) {
this.logger.log(LOG_LEVEL.ERROR, e.message);
this.errorHandler.handleError(e);
return -1;
}
}
/**
* Remove a previously added notification callback
* @param {number} listenerId ID of listener to be removed
* @returns {boolean} Returns true if the listener was found and removed, and false
* otherwise.
*/
removeNotificationListener(listenerId: number): boolean {
try {
let indexToRemove: number | undefined;
let typeToRemove: string | undefined;
Object.keys(this.notificationListeners).some(
(notificationType) => {
const listenersForType = this.notificationListeners[notificationType];
(listenersForType || []).every((listenerEntry, i) => {
if (listenerEntry.id === listenerId) {
indexToRemove = i;
typeToRemove = notificationType;
return false;
}
return true;
});
if (indexToRemove !== undefined && typeToRemove !== undefined) {
return true;
}
return false;
}
);
if (indexToRemove !== undefined && typeToRemove !== undefined) {
this.notificationListeners[typeToRemove].splice(indexToRemove, 1);
return true;
}
} catch (e: any) {
this.logger.log(LOG_LEVEL.ERROR, e.message);
this.errorHandler.handleError(e);
}
return false;
}
/**
* Removes all previously added notification listeners, for all notification types
*/
clearAllNotificationListeners(): void {
try {
objectValues(NOTIFICATION_TYPES).forEach(
(notificationTypeEnum) => {
this.notificationListeners[notificationTypeEnum] = [];
}
);
} catch (e: any) {
this.logger.log(LOG_LEVEL.ERROR, e.message);
this.errorHandler.handleError(e);
}
}
/**
* Remove all previously added notification listeners for the argument type
* @param {NOTIFICATION_TYPES} notificationType One of NOTIFICATION_TYPES
*/
clearNotificationListeners(notificationType: NOTIFICATION_TYPES): void {
try {
this.notificationListeners[notificationType] = [];
} catch (e: any) {
this.logger.log(LOG_LEVEL.ERROR, e.message);
this.errorHandler.handleError(e);
}
}
/**
* Fires notifications for the argument type. All registered callbacks for this type will be
* called. The notificationData object will be passed on to callbacks called.
* @param {string} notificationType One of NOTIFICATION_TYPES
* @param {Object} notificationData Will be passed to callbacks called
*/
sendNotifications<T extends ListenerPayload>(
notificationType: string,
notificationData?: T
): void {
try {
(this.notificationListeners[notificationType] || []).forEach(
(listenerEntry) => {
const callback = listenerEntry.callback;
try {
callback(notificationData);
} catch (ex: any) {
this.logger.log(
LOG_LEVEL.ERROR,
LOG_MESSAGES.NOTIFICATION_LISTENER_EXCEPTION,
MODULE_NAME,
notificationType,
ex.message,
);
}
}
);
} catch (e: any) {
this.logger.log(LOG_LEVEL.ERROR, e.message);
this.errorHandler.handleError(e);
}
}
}
/**
* Create an instance of NotificationCenter
* @param {NotificationCenterOptions} options
* @returns {NotificationCenter} An instance of NotificationCenter
*/
export function createNotificationCenter(options: NotificationCenterOptions): NotificationCenter {
return new NotificationCenter(options);
}
export interface NotificationSender {
// TODO[OASIS-6649]: Don't use any type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sendNotifications(notificationType: NOTIFICATION_TYPES, notificationData?: any): void
}