This repository has been archived by the owner on Jun 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathua.ts
72 lines (61 loc) · 1.63 KB
/
ua.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
import config from 'config';
import { PartialUser, User } from 'discord.js';
import fetch from 'node-fetch';
import { v4 as uuid } from 'uuid';
import { Logger } from './logger';
import { isDevMode } from './utils';
const clientId = uuid();
export function getVisitor(user: User | PartialUser): Visitor {
return new Visitor(config.get('measurementProtocol.measurementId'), config.get('measurementProtocol.apiSecret'), user.id);
}
interface Event {
name: string;
params: Record<string, any>;
}
export class Visitor {
private queue: Event[] = [];
constructor(
private measurementId: string,
private apiSecret: string,
private userId: string,
) { }
event(name: string, params: Record<string, any>) {
const event: Event = {
name,
params,
};
this.queue.push(event);
return this;
}
exception(description: string, fatal: boolean) {
return this.event('exception', {
description,
fatal,
});
}
async send() {
if (!this.measurementId || !this.apiSecret) return;
const debug = isDevMode() ? 'debug/' : '';
const url = `https://www.google-analytics.com/${debug}mp/collect?measurement_id=${this.measurementId}&api_secret=${this.apiSecret}`;
try {
while (this.queue.length > 0) {
const events = this.queue.splice(0, Math.min(this.queue.length, 25));
const body = {
client_id: clientId,
userId: this.userId,
events,
};
const res = await fetch(url, {
method: "POST",
body: JSON.stringify(body),
});
if (isDevMode()) {
const json = await res.json();
Logger.debug('[Visitor]', json);
}
}
} catch (error) {
Logger.error('[Visitor]', error);
}
}
}