budibase/packages/builder/src/analytics/PosthogClient.js

81 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-09-21 12:47:14 +02:00
import posthog from "posthog-js"
import { Events } from "./constants"
export default class PosthogClient {
constructor(token, url) {
this.token = token
this.url = url
}
init() {
if (!this.token || !this.url) return
posthog.init(this.token, {
autocapture: false,
capture_pageview: true,
2021-09-21 12:47:14 +02:00
api_host: this.url,
})
posthog.set_config({ persistence: "cookie" })
this.initialised = true
}
2021-09-21 21:28:33 +02:00
/**
2021-09-21 21:47:04 +02:00
* Set the posthog context to the current user
2021-09-21 21:28:33 +02:00
* @param {String} id - unique user id
*/
2021-09-21 12:47:14 +02:00
identify(id) {
if (!this.initialised) return
posthog.identify(id)
}
2021-09-21 21:28:33 +02:00
/**
* Update user metadata associated with current user in posthog
* @param {Object} meta - user fields
*/
2021-09-21 12:47:14 +02:00
updateUser(meta) {
if (!this.initialised) return
posthog.people.set(meta)
}
2021-09-21 21:28:33 +02:00
/**
* Capture analytics events and send them to posthog.
* @param {String} event - event identifier
* @param {Object} props - properties for the event
*/
2021-09-21 12:47:14 +02:00
captureEvent(eventName, props) {
if (!this.initialised) return
props.sourceApp = "builder"
posthog.capture(eventName, props)
}
2021-09-21 21:28:33 +02:00
/**
* Submit NPS feedback to posthog.
* @param {Object} values - NPS Values
*/
2021-09-21 12:47:14 +02:00
npsFeedback(values) {
if (!this.initialised) return
localStorage.setItem(Events.NPS.SUBMITTED, Date.now())
const prefixedFeedback = {}
for (let key in values) {
prefixedFeedback[`feedback_${key}`] = values[key]
}
posthog.capture(Events.NPS.SUBMITTED, prefixedFeedback)
}
2021-09-21 21:28:33 +02:00
/**
2021-09-21 21:47:04 +02:00
* Reset posthog user back to initial state on logout.
2021-09-21 21:28:33 +02:00
*/
logout() {
if (!this.initialised) return
posthog.reset()
}
}