1
0
Fork 0
mirror of synced 2024-09-19 18:59:06 +12:00
budibase/packages/builder/src/analytics/PosthogClient.js

87 lines
1.8 KiB
JavaScript
Raw Normal View History

2021-09-21 22:47:14 +12:00
import posthog from "posthog-js"
import { Events } from "./constants"
2022-08-02 21:52:09 +12:00
import { get } from "svelte/store"
import { admin } from "../stores/portal"
2021-09-21 22:47:14 +12:00
export default class PosthogClient {
2022-06-07 02:27:29 +12:00
constructor(token) {
2021-09-21 22:47:14 +12:00
this.token = token
}
init() {
2022-06-07 02:27:29 +12:00
if (!this.token) return
2021-09-21 22:47:14 +12:00
2022-08-02 21:52:09 +12:00
// enable page views in cloud only
let capturePageViews = false
if (get(admin).cloud) {
capturePageViews = true
}
2021-09-21 22:47:14 +12:00
posthog.init(this.token, {
autocapture: false,
2022-08-02 21:52:09 +12:00
capture_pageview: capturePageViews,
2021-09-21 22:47:14 +12:00
})
posthog.set_config({ persistence: "cookie" })
this.initialised = true
}
2021-09-22 07:28:33 +12:00
/**
2021-09-22 07:47:04 +12:00
* Set the posthog context to the current user
2021-09-22 07:28:33 +12:00
* @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
/**
2021-09-22 07:47:04 +12:00
* Reset posthog user back to initial state on logout.
2021-09-22 07:28:33 +12:00
*/
logout() {
if (!this.initialised) return
posthog.reset()
}
}