1
0
Fork 0
mirror of synced 2024-09-20 03:08:18 +12:00
budibase/packages/builder/src/analytics/PosthogClient.js

81 lines
1.7 KiB
JavaScript
Raw Normal View History

2021-09-21 22:47:14 +12: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: false,
api_host: this.url,
})
posthog.set_config({ persistence: "cookie" })
this.initialised = true
}
2021-09-22 07:28:33 +12:00
/**
* Set the posthog context to the current user
* @param {String} id - unique user id
*/
2021-09-21 22:47:14 +12:00
identify(id) {
if (!this.initialised) return
posthog.identify(id)
}
2021-09-22 07:28:33 +12:00
/**
* Update user metadata associated with current user in posthog
* @param {Object} meta - user fields
*/
2021-09-21 22:47:14 +12:00
updateUser(meta) {
if (!this.initialised) return
posthog.people.set(meta)
}
2021-09-22 07:28:33 +12:00
/**
* Capture analytics events and send them to posthog.
* @param {String} event - event identifier
* @param {Object} props - properties for the event
*/
2021-09-21 22:47:14 +12:00
captureEvent(eventName, props) {
if (!this.initialised) return
props.sourceApp = "builder"
posthog.capture(eventName, props)
}
2021-09-22 07:28:33 +12:00
/**
* Submit NPS feedback to posthog.
* @param {Object} values - NPS Values
*/
2021-09-21 22:47:14 +12: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-22 07:28:33 +12:00
/**
* Reset posthog user back to initial state on logout.
*/
logout() {
if (!this.initialised) return
posthog.reset()
}
}