-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
rudderstackClient.ts
99 lines (83 loc) · 2.5 KB
/
rudderstackClient.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import RudderAnalytics from '@expo/rudder-sdk-node';
import os from 'os';
import { v4 as uuidv4 } from 'uuid';
import { EXPO_LOCAL, EXPO_STAGING, EXPO_NO_TELEMETRY } from '../env';
import UserSettings from '../user/UserSettings';
const PLATFORM_TO_ANALYTICS_PLATFORM: { [platform: string]: string } = {
darwin: 'Mac',
win32: 'Windows',
linux: 'Linux',
};
let client: RudderAnalytics | null = null;
let identified = false;
let identifyData: {
userId: string;
deviceId: string;
traits: Record<string, any>;
} | null = null;
function getClient(): RudderAnalytics {
if (client) {
return client;
}
client = new RudderAnalytics(
EXPO_STAGING || EXPO_LOCAL ? '24TKICqYKilXM480mA7ktgVDdea' : '24TKR7CQAaGgIrLTgu3Fp4OdOkI', // expo unified
'https://cdp.expo.dev/v1/batch',
{
flushInterval: 300,
}
);
// Install flush on exit...
process.on('SIGINT', () => client?.flush?.());
process.on('SIGTERM', () => client?.flush?.());
return client;
}
export async function setUserDataAsync(userId: string, traits: Record<string, any>): Promise<void> {
if (EXPO_NO_TELEMETRY) {
return;
}
const savedDeviceId = await UserSettings.getAsync('analyticsDeviceId', null);
const deviceId = savedDeviceId ?? uuidv4();
if (!savedDeviceId) {
await UserSettings.setAsync('analyticsDeviceId', deviceId);
}
identifyData = {
userId,
deviceId,
traits,
};
ensureIdentified();
}
export function logEvent(event: 'action', properties: Record<string, any> = {}): void {
if (EXPO_NO_TELEMETRY) {
return;
}
ensureIdentified();
const { userId, deviceId } = identifyData ?? {};
const commonEventProperties = { source_version: process.env.__EXPO_VERSION, source: 'expo' };
const identity = { userId: userId ?? undefined, anonymousId: deviceId ?? uuidv4() };
getClient().track({
event,
properties: { ...properties, ...commonEventProperties },
...identity,
context: getContext(),
});
}
function ensureIdentified(): void {
if (EXPO_NO_TELEMETRY || identified || !identifyData) {
return;
}
getClient().identify({
userId: identifyData.userId,
anonymousId: identifyData.deviceId,
traits: identifyData.traits,
});
identified = true;
}
function getContext(): Record<string, any> {
const platform = PLATFORM_TO_ANALYTICS_PLATFORM[os.platform()] || os.platform();
return {
os: { name: platform, version: os.release() },
device: { type: platform, model: platform },
app: { name: 'expo', version: process.env.__EXPO_VERSION },
};
}