This repository has been archived by the owner on Jun 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsegment.ts
64 lines (60 loc) · 1.56 KB
/
segment.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
import { BaseProvider } from './base';
import Segment from 'analytics-node';
import { SegmentConfig, EventAction, PageAction } from '@blockstack/stats';
import { Request } from 'express';
import { getUserAgent } from '../utils';
export class SegmentProvider extends BaseProvider {
static async event(eventAction: EventAction, req: Request) {
const client = this.getClient(eventAction.provider);
const { eventData, context } = eventAction;
const { name, ...rest } = eventData;
client.track({
event: name,
anonymousId: eventAction.id,
context: {
...context,
...this.getUAContext(req),
},
properties: {
...rest,
},
});
return Promise.resolve();
}
static async page(pageAction: PageAction, req: Request) {
const client = this.getClient(pageAction.provider);
const { pageData, context } = pageAction;
const { name, ...rest } = pageData;
client.page({
context: {
...context,
...this.getUAContext(req),
},
anonymousId: pageAction.id,
name,
properties: {
...rest,
},
});
return Promise.resolve();
}
static getClient(provider: SegmentConfig) {
return new Segment(provider.writeKey || '');
}
static getUAContext(req: Request) {
const ua = getUserAgent(req);
if (!ua) {
return {};
}
const os = ua.getOS();
const device = ua.getDevice();
return {
os,
device: {
manufacturer: device.vendor,
model: device.model,
type: device.type,
},
};
}
}