-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAnalyticsContext.ts
45 lines (38 loc) · 1.39 KB
/
AnalyticsContext.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
import deepmerge from 'deepmerge';
import {DataMap, PromiseOrValue, AnalyticsEventModel} from './types';
export type AnalyticsFilter = (model: AnalyticsEventModel) => PromiseOrValue<void>;
export class AnalyticsContext {
constructor(
readonly Scopes: string[] = [],
readonly ExtraData: DataMap = {},
readonly MetaData: DataMap = {},
readonly Identities: DataMap = {},
readonly Filters: AnalyticsFilter[] = [],
) {}
union(analyticsContext?: Partial<AnalyticsContext>): AnalyticsContext {
if (!analyticsContext) {
return this;
}
return new AnalyticsContext(
this.Scopes.concat(analyticsContext.Scopes || []),
deepmerge(this.ExtraData, analyticsContext.ExtraData || {}),
deepmerge(this.MetaData, analyticsContext.MetaData || {}),
deepmerge(this.Identities, analyticsContext.Identities || {}),
this.Filters.concat(analyticsContext.Filters || []),
);
}
async toEventModel(eventName: string): Promise<AnalyticsEventModel> {
const eventModel: AnalyticsEventModel = {
Name: eventName,
Scope: this.Scopes.join('_'),
ExtraData: deepmerge({}, this.ExtraData),
MetaData: deepmerge({}, this.MetaData),
Identities: deepmerge({}, this.Identities),
};
await this.Filters.reduce(async (acc, filter) => {
await acc;
await filter(eventModel);
}, Promise.resolve());
return eventModel;
}
}