|
1
|
import { |
|
2
|
Logger, |
|
3
|
PosthogAnalyticsServiceOptions, |
|
4
|
ProviderIdentifyAnalyticsEventDTO, |
|
5
|
ProviderTrackAnalyticsEventDTO, |
|
6
|
} from "@medusajs/framework/types" |
|
7
|
import { AbstractAnalyticsProviderService } from "@medusajs/framework/utils" |
|
8
|
import { PostHog } from "posthog-node" |
|
9
|
|
|
10
|
type InjectedDependencies = { |
|
11
|
logger: Logger |
|
12
|
} |
|
13
|
|
|
14
|
export class PosthogAnalyticsService extends AbstractAnalyticsProviderService { |
|
15
|
static identifier = "analytics-posthog" |
|
16
|
protected config_: PosthogAnalyticsServiceOptions |
|
17
|
protected logger_: Logger |
|
18
|
protected client_: PostHog |
|
19
|
|
|
20
|
constructor( |
|
21
|
{ logger }: InjectedDependencies, |
|
22
|
options: PosthogAnalyticsServiceOptions |
|
23
|
) { |
|
24
|
super() |
|
25
|
this.config_ = options |
|
26
|
this.logger_ = logger |
|
27
|
|
|
28
|
if (!options.posthogEventsKey) { |
|
29
|
throw new Error("Posthog API key is not set, but is required") |
|
30
|
} |
|
31
|
|
|
32
|
this.client_ = new PostHog(options.posthogEventsKey, { |
|
33
|
host: options.posthogHost || "https://eu.i.posthog.com", |
|
34
|
}) |
|
35
|
} |
|
36
|
|
|
37
|
async track(data: ProviderTrackAnalyticsEventDTO): Promise<void> { |
|
38
|
if (!data.event) { |
|
39
|
throw new Error( |
|
40
|
"Event name is required when tracking an event with Posthog" |
|
41
|
) |
|
42
|
} |
|
43
|
|
|
44
|
if (!data.actor_id) { |
|
45
|
throw new Error( |
|
46
|
"Actor ID is required when tracking an event with Posthog" |
|
47
|
) |
|
48
|
} |
|
49
|
|
|
50
|
if (data.group?.id && !data.group?.type) { |
|
51
|
throw new Error( |
|
52
|
"Group type is required if passing group id when tracking an event with Posthog" |
|
53
|
) |
|
54
|
} |
|
55
|
|
|
56
|
this.client_.capture({ |
|
57
|
event: data.event, |
|
58
|
distinctId: data.actor_id, |
|
59
|
properties: data.properties, |
|
60
|
groups: data.group?.id |
|
61
|
? { [data.group.type!]: data.group.id } |
|
62
|
: undefined, |
|
63
|
}) |
|
64
|
} |
|
65
|
|
|
66
|
async identify(data: ProviderIdentifyAnalyticsEventDTO): Promise<void> { |
|
67
|
if ("group" in data) { |
|
68
|
this.client_.groupIdentify({ |
|
69
|
groupKey: data.group.id!, |
|
70
|
groupType: data.group.type!, |
|
71
|
properties: data.properties, |
|
72
|
distinctId: data.actor_id, |
|
73
|
}) |
|
74
|
} else if (data.actor_id) { |
|
75
|
this.client_.identify({ |
|
76
|
distinctId: data.actor_id, |
|
77
|
properties: data.properties, |
|
78
|
}) |
|
79
|
} else { |
|
80
|
throw new Error( |
|
81
|
"Actor or group is required when identifying an entity with Posthog" |
|
82
|
) |
|
83
|
} |
|
84
|
} |
|
85
|
|
|
86
|
async shutdown() { |
|
87
|
await this.client_.shutdown() |
|
88
|
} |
|
89
|
} |