forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathamplitude.ts
More file actions
101 lines (85 loc) · 2.59 KB
/
amplitude.ts
File metadata and controls
101 lines (85 loc) · 2.59 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
import { debug, global } from './utils';
import delay from '../delay';
// After 30min no event we mark a session
const NEW_SESSION_TIME = 1000 * 60 * 30;
const getLastTimeEventSent = () => {
const lastTime = localStorage.getItem('csb-last-event-sent');
if (lastTime === null) {
return 0;
}
return +lastTime;
};
const markLastTimeEventSent = () => {
localStorage.setItem('csb-last-event-sent', Date.now().toString());
};
const getAmplitude = async (): Promise<any | false> => {
if (process.env.NODE_ENV !== 'production') {
return false;
}
for (let i = 0; i < 10; i++) {
if (
typeof global.amplitude !== 'undefined' &&
global.amplitude.getInstance()._storageSuffix
) {
return global.amplitude;
}
// eslint-disable-next-line no-await-in-loop
await delay(1000);
}
return false;
};
export const identify = async (key: string, value: any) => {
const amplitude = await getAmplitude();
if (amplitude) {
const identity = new amplitude.Identify();
identity.set(key, value);
amplitude.identify(identity);
debug('[Amplitude] Identifying', key, value);
} else {
debug('[Amplitude] NOT identifying because Amplitude is not loaded');
}
};
export const setUserId = async (userId: string) => {
const amplitude = await getAmplitude();
if (amplitude) {
debug('[Amplitude] Setting User ID', userId);
identify('userId', userId);
amplitude.getInstance().setUserId(userId);
} else {
debug('[Amplitude] NOT setting userid because Amplitude is not loaded');
}
};
export const resetUserId = async () => {
const amplitude = await getAmplitude();
if (amplitude) {
debug('[Amplitude] Resetting User ID');
identify('userId', null);
if (
amplitude.getInstance().options &&
amplitude.getInstance().options.userId
) {
amplitude.getInstance().setUserId(null);
amplitude.getInstance().regenerateDeviceId();
}
} else {
debug('[Amplitude] NOT resetting user id because Amplitude is not loaded');
}
};
export const track = async (eventName: string, data: any) => {
const amplitude = await getAmplitude();
if (amplitude) {
const currentTime = Date.now();
if (currentTime - getLastTimeEventSent() > NEW_SESSION_TIME) {
// We send a separate New Session event if people have been inactive for a while
amplitude.logEvent('New Session');
}
markLastTimeEventSent();
debug('[Amplitude] Tracking', eventName, data);
amplitude.logEvent(eventName, data);
} else {
debug(
'[Amplitude] NOT tracking because Amplitude is not loaded',
eventName
);
}
};