-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathEventsController.ts
More file actions
75 lines (65 loc) · 2.05 KB
/
EventsController.ts
File metadata and controls
75 lines (65 loc) · 2.05 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
import { proxy, subscribe as sub } from 'valtio';
import { ApiController } from './ApiController';
import { OptionsController } from './OptionsController';
import { CoreHelperUtil } from '../utils/CoreHelperUtil';
import { FetchUtil } from '../utils/FetchUtil';
import type { Event, EventName } from '../utils/TypeUtil';
// -- Helpers ------------------------------------------- //
const baseUrl = CoreHelperUtil.getAnalyticsUrl();
const api = new FetchUtil({ baseUrl });
const excluded = ['MODAL_CREATED'];
// -- Types --------------------------------------------- //
export interface EventsControllerState {
timestamp: number;
data: Event;
}
// -- State --------------------------------------------- //
const state = proxy<EventsControllerState>({
timestamp: Date.now(),
data: {
type: 'track',
event: 'MODAL_CREATED' // just for init purposes
}
});
// -- Controller ---------------------------------------- //
export const EventsController = {
state,
subscribe(callback: (newState: EventsControllerState) => void) {
return sub(state, () => callback(state));
},
subscribeEvent(event: EventName, callback: (newEvent: EventsControllerState) => void) {
return sub(state, () => {
if (state.data.event === event) {
callback(state);
}
});
},
async _sendAnalyticsEvent(data: EventsControllerState['data'], timestamp: number) {
if (excluded.includes(data.event)) {
return;
}
try {
await api.post({
path: '/e',
headers: ApiController._getApiHeaders(),
body: {
eventId: CoreHelperUtil.getUUID(),
bundleId: CoreHelperUtil.getBundleId(),
timestamp,
props: data
}
});
} catch {
// Catch silently
}
},
async sendEvent(data: EventsControllerState['data']) {
const timestamp = Date.now();
state.timestamp = timestamp;
state.data = data;
await ApiController.state.prefetchPromise;
if (OptionsController.state.enableAnalytics) {
EventsController._sendAnalyticsEvent(data, timestamp);
}
}
};