|
1
|
import { MedusaError } from "@medusajs/framework/utils" |
|
2
|
import { |
|
3
|
Constructor, |
|
4
|
IAnalyticsProvider, |
|
5
|
ProviderIdentifyAnalyticsEventDTO, |
|
6
|
ProviderTrackAnalyticsEventDTO, |
|
7
|
} from "@medusajs/types" |
|
8
|
|
|
9
|
export const AnalyticsProviderIdentifierRegistrationName = |
|
10
|
"analytics_providers_identifier" |
|
11
|
|
|
12
|
export const AnalyticsProviderRegistrationPrefix = "aly_" |
|
13
|
|
|
14
|
type InjectedDependencies = { |
|
15
|
[ |
|
16
|
key: `${typeof AnalyticsProviderRegistrationPrefix}${string}` |
|
17
|
]: IAnalyticsProvider |
|
18
|
} |
|
19
|
|
|
20
|
export default class AnalyticsProviderService { |
|
21
|
protected readonly analyticsProvider_: IAnalyticsProvider |
|
22
|
|
|
23
|
constructor(container: InjectedDependencies) { |
|
24
|
const analyticsProviderKeys = Object.keys(container).filter((k) => |
|
25
|
k.startsWith(AnalyticsProviderRegistrationPrefix) |
|
26
|
) |
|
27
|
|
|
28
|
if (analyticsProviderKeys.length !== 1) { |
|
29
|
throw new MedusaError( |
|
30
|
MedusaError.Types.INVALID_DATA, |
|
31
|
`Analytics module should be initialized with exactly one provider` |
|
32
|
) |
|
33
|
} |
|
34
|
|
|
35
|
this.analyticsProvider_ = container[analyticsProviderKeys[0]] |
|
36
|
} |
|
37
|
|
|
38
|
static getRegistrationIdentifier( |
|
39
|
providerClass: Constructor<IAnalyticsProvider>, |
|
40
|
optionName?: string |
|
41
|
) { |
|
42
|
return `${(providerClass as any).identifier}_${optionName}` |
|
43
|
} |
|
44
|
|
|
45
|
async track(data: ProviderTrackAnalyticsEventDTO): Promise<void> { |
|
46
|
await this.analyticsProvider_.track(data) |
|
47
|
} |
|
48
|
|
|
49
|
async identify(data: ProviderIdentifyAnalyticsEventDTO): Promise<void> { |
|
50
|
await this.analyticsProvider_.identify(data) |
|
51
|
} |
|
52
|
|
|
53
|
async shutdown(): Promise<void> { |
|
54
|
await this.analyticsProvider_.shutdown?.() |
|
55
|
} |
|
56
|
} |