/
Telemetry.ts
73 lines (63 loc) · 1.82 KB
/
Telemetry.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
import { Extension, Settings } from '.';
import { EXTENSION_BETA_ID, EXTENSION_ID, SETTING_TELEMETRY_DISABLE } from '../constants';
const METRICS_URL = 'https://frontmatter.codes/api/metrics';
export class Telemetry {
private static instance: Telemetry;
private extTitle: string;
private extVersion: string;
private events: any[] = [];
private timeout: NodeJS.Timeout | undefined;
private constructor() {
const extension = Extension.getInstance();
this.extTitle = extension.isBetaVersion() ? EXTENSION_BETA_ID : EXTENSION_ID;
this.extVersion = extension.version;
}
public static getInstance(): Telemetry {
if (!Telemetry.instance) {
Telemetry.instance = new Telemetry();
}
return Telemetry.instance;
}
/**
* Send metrics to our own database
* @param eventName
* @param properties
* @returns
*/
public static send(eventName: string, properties?: any) {
const isDisabled = Settings.get<boolean>(SETTING_TELEMETRY_DISABLE);
if (isDisabled) {
return;
}
const instance = Telemetry.getInstance();
instance.events.push({
name: eventName,
extName: instance.extTitle,
version: instance.extVersion,
properties
});
instance.debounceMetrics();
}
/**
* Debounce the metrics by 1 second
*/
private async debounceMetrics() {
const instance = Telemetry.getInstance();
// Check if timeout was defined
if (instance.timeout) {
clearTimeout(instance.timeout);
}
// Set a new timeout
instance.timeout = setTimeout(async () => {
await fetch(METRICS_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.events)
});
// Reset the events
this.events = [];
}, 1000) as any as NodeJS.Timeout;
}
}