-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuid2CallbackManager.ts
79 lines (72 loc) · 2.53 KB
/
uid2CallbackManager.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
78
79
import { UID2SdkBase } from './uid2Sdk';
import { Uid2Identity } from './Uid2Identity';
import { Logger } from './sdk/logger';
export enum EventType {
InitCompleted = 'InitCompleted',
IdentityUpdated = 'IdentityUpdated',
SdkLoaded = 'SdkLoaded',
}
export type Uid2CallbackPayload = SdkLoadedPayload | PayloadWithIdentity;
export type Uid2CallbackHandler = (event: EventType, payload: Uid2CallbackPayload) => void;
type SdkLoadedPayload = Record<string, never>;
type PayloadWithIdentity = {
identity: Uid2Identity | null;
};
export class Uid2CallbackManager {
private _getIdentity: () => Uid2Identity | null | undefined;
private _logger: Logger;
private _sdk: UID2SdkBase;
private _productName: string;
constructor(
sdk: UID2SdkBase,
productName: string,
getIdentity: () => Uid2Identity | null | undefined,
logger: Logger
) {
this._productName = productName;
this._logger = logger;
this._getIdentity = getIdentity;
this._sdk = sdk;
this._sdk.callbacks.push = this.callbackPushInterceptor.bind(this);
}
private static _sentSdkLoaded: Record<string, boolean> = {}; //TODO: This needs to be fixed for EUID!
private _sentInit = false;
private callbackPushInterceptor(...args: Uid2CallbackHandler[]) {
for (const c of args) {
if (Uid2CallbackManager._sentSdkLoaded[this._productName])
this.safeRunCallback(c, EventType.SdkLoaded, {});
if (this._sentInit)
this.safeRunCallback(c, EventType.InitCompleted, {
identity: this._getIdentity() ?? null,
});
}
return Array.prototype.push.apply(this._sdk.callbacks, args);
}
public runCallbacks(event: EventType, payload: Uid2CallbackPayload) {
if (event === EventType.InitCompleted) this._sentInit = true;
if (event === EventType.SdkLoaded) Uid2CallbackManager._sentSdkLoaded[this._productName] = true;
if (!this._sentInit && event !== EventType.SdkLoaded) return;
const enrichedPayload = {
...payload,
identity: this._getIdentity() ?? null,
};
for (const callback of this._sdk.callbacks) {
this.safeRunCallback(callback, event, enrichedPayload);
}
}
private safeRunCallback(
callback: Uid2CallbackHandler,
event: EventType,
payload: Uid2CallbackPayload
) {
if (typeof callback === 'function') {
try {
callback(event, payload);
} catch (exception) {
this._logger.warn('SDK callback threw an exception', exception);
}
} else {
this._logger.warn("An SDK callback was supplied which isn't a function.");
}
}
}