feat: Add an analytics module and local and posthog providers (#12505)

* feat: Add an analytics module and local and posthog providers

* fix: Add tests and wire up in missing places

* fix: Address feedback and add missing module typing

* fix: Address feedback and add missing module typing

---------

Co-authored-by: Adrien de Peretti <adrien.deperetti@gmail.com>
Co-authored-by: Oli Juhl <59018053+olivermrbl@users.noreply.github.com>
This commit is contained in:
Stevche Radevski
2025-05-19 19:57:13 +02:00
committed by GitHub
co-authored by Adrien de Peretti Oli Juhl
parent 52bd9f9a53
commit b9a51e217d
49 changed files with 1009 additions and 0 deletions
@@ -0,0 +1,52 @@
import {
TrackAnalyticsEventDTO,
IdentifyAnalyticsEventDTO,
} from "@medusajs/types"
import AnalyticsProviderService from "./provider-service"
import { MedusaError } from "../../../../core/utils/dist/common"
type InjectedDependencies = {
analyticsProviderService: AnalyticsProviderService
}
export default class AnalyticsService {
protected readonly analyticsProviderService_: AnalyticsProviderService
constructor({ analyticsProviderService }: InjectedDependencies) {
this.analyticsProviderService_ = analyticsProviderService
}
__hooks = {
onApplicationShutdown: async () => {
await this.analyticsProviderService_.shutdown()
},
}
getProvider() {
return this.analyticsProviderService_
}
async track(data: TrackAnalyticsEventDTO): Promise<void> {
try {
await this.analyticsProviderService_.track(data)
} catch (error) {
throw new MedusaError(
MedusaError.Types.UNEXPECTED_STATE,
`Error tracking event for ${data.event}: ${error.message}`
)
}
}
async identify(data: IdentifyAnalyticsEventDTO): Promise<void> {
try {
await this.analyticsProviderService_.identify(data)
} catch (error) {
throw new MedusaError(
MedusaError.Types.UNEXPECTED_STATE,
`Error identifying event for ${
"group" in data ? data.group.id : data.actor_id
}: ${error.message}`
)
}
}
}