diff --git a/packages/api/src/server.ts b/packages/api/src/server.ts index 3fa1fdb9e..23791842c 100755 --- a/packages/api/src/server.ts +++ b/packages/api/src/server.ts @@ -74,6 +74,7 @@ export const createApp = (): Express => { if (client) { httpContext.set('client', client) } + // TODO: get client info from user agent next() }) diff --git a/packages/api/src/utils/analytics.ts b/packages/api/src/utils/analytics.ts index 8b3717cb8..d59b1622a 100644 --- a/packages/api/src/utils/analytics.ts +++ b/packages/api/src/utils/analytics.ts @@ -1,4 +1,42 @@ +import httpContext from 'express-http-context2' import { PostHog } from 'posthog-node' import { env } from '../env' -export const analytics = new PostHog(env.posthog.apiKey || 'test') +interface AnalyticEvent { + distinctId: string + event: string + properties?: Record +} + +interface AnalyticClient { + capture: (event: AnalyticEvent) => void + shutdownAsync?: () => Promise +} + +class PostHogClient implements AnalyticClient { + private client: PostHog + + constructor(apiKey: string) { + this.client = new PostHog(apiKey) + } + + capture({ distinctId, event, properties }: AnalyticEvent) { + // get client from request context + const client = httpContext.get('client') || 'other' + + this.client.capture({ + distinctId, + event, + properties: { + ...properties, + client, + }, + }) + } + + async shutdownAsync() { + return this.client.shutdownAsync() + } +} + +export const analytics = new PostHogClient(env.posthog.apiKey || 'test')