1
0
Fork 0
mirror of synced 2024-06-28 11:00:55 +12:00
budibase/packages/backend-core/src/events/processors/PosthogProcessor.ts

81 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-05-05 19:32:14 +12:00
import PostHog from "posthog-node"
2022-06-01 08:04:41 +12:00
import { Event, Identity, Group, BaseEvent } from "@budibase/types"
import { EventProcessor } from "./types"
import env from "../../environment"
2022-06-01 08:04:41 +12:00
import context from "../../context"
const pkg = require("../../../package.json")
2022-05-05 19:32:14 +12:00
export default class PosthogProcessor implements EventProcessor {
2022-05-05 19:32:14 +12:00
posthog: PostHog
constructor(token: string | undefined) {
if (!token) {
throw new Error("Posthog token is not defined")
}
this.posthog = new PostHog(token)
}
2022-05-24 09:14:44 +12:00
async processEvent(
event: Event,
identity: Identity,
2022-06-01 08:04:41 +12:00
properties: BaseEvent,
timestamp?: string | number
2022-05-24 09:14:44 +12:00
): Promise<void> {
properties.version = pkg.version
properties.service = env.SERVICE
properties.environment = env.DEPLOYMENT_ENVIRONMENT
2022-06-01 08:04:41 +12:00
const appId = context.getAppId()
if (appId) {
properties.appId = appId
}
const payload: any = { distinctId: identity.id, event, properties }
2022-06-01 08:04:41 +12:00
if (timestamp) {
payload.timestamp = new Date(timestamp)
}
// add groups to the event
if (identity.installationId || identity.tenantId) {
payload.groups = {}
if (identity.installationId) {
payload.groups.installation = identity.installationId
2022-06-01 08:04:41 +12:00
payload.properties.installationId = identity.installationId
}
if (identity.tenantId) {
payload.groups.tenant = identity.tenantId
2022-06-01 08:04:41 +12:00
payload.properties.tenantId = identity.tenantId
}
}
this.posthog.capture(payload)
2022-05-05 19:32:14 +12:00
}
2022-05-26 08:32:08 +12:00
async identify(identity: Identity, timestamp?: string | number) {
const payload: any = { distinctId: identity.id, properties: identity }
if (timestamp) {
payload.timestamp = new Date(timestamp)
}
this.posthog.identify(payload)
2022-05-05 19:32:14 +12:00
}
async identifyGroup(group: Group, timestamp?: string | number) {
const payload: any = {
distinctId: group.id,
groupType: group.type,
groupKey: group.id,
properties: group,
}
if (timestamp) {
payload.timestamp = new Date(timestamp)
}
this.posthog.groupIdentify(payload)
}
2022-05-05 19:32:14 +12:00
shutdown() {
this.posthog.shutdown()
}
}