/
events.js
71 lines (65 loc) · 1.81 KB
/
events.js
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
import { fetch } from 'whatwg-fetch';
import cookie from 'component-cookie';
import uuidv4 from 'uuid/v4';
let flushPromise = null;
let trackEvents = [];
const track = async (event) => {
if (!cookie('playground_anonymous')) {
cookie('playground_anonymous', uuidv4());
}
trackEvents.push({
...event,
id: uuidv4(),
clientAnonymousId: cookie('playground_anonymous'),
clientTimestamp: new Date().toJSON()
});
const flush = async (toFlush, retries) => {
if (!toFlush) {
toFlush = trackEvents;
trackEvents = [];
}
if (!toFlush.length) {
return null;
}
if (retries == null) {
retries = 10;
}
try {
const sentAt = new Date().toJSON();
const result = await fetch('https://track.cube.dev/track', {
method: 'post',
body: JSON.stringify(toFlush.map(r => ({ ...r, sentAt }))),
headers: { 'Content-Type': 'application/json' },
});
if (result.status !== 200 && retries > 0) {
return flush(toFlush, retries - 1);
}
// console.log(await result.json());
} catch (e) {
if (retries > 0) {
return flush(toFlush, retries - 1);
}
// console.log(e);
}
return null;
};
const currentPromise = (flushPromise || Promise.resolve()).then(() => flush()).then(() => {
if (currentPromise === flushPromise) {
flushPromise = null;
}
});
flushPromise = currentPromise;
return flushPromise;
};
export const setAnonymousId = (anonymousId, props) => {
track({ event: 'identify', anonymousId, ...props });
};
export const event = (name, params) => {
track({ event: name, ...params });
};
export const playgroundAction = (name, options) => {
event('Playground Action', { name, ...options });
};
export const page = (path) => {
track({ event: 'page', ...path });
};