budibase/packages/builder/src/analytics.js

61 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-07-14 17:00:58 +02:00
import * as Sentry from "@sentry/browser"
import posthog from "posthog-js"
import api from "builderStore/api"
2020-07-14 17:00:58 +02:00
const analyticsEnabled = process.env.NODE_ENV === "production"
2020-07-14 17:00:58 +02:00
function activate() {
if (!analyticsEnabled) return
2020-07-14 17:00:58 +02:00
Sentry.init({ dsn: process.env.SENTRY_DSN })
if (!process.env.POSTHOG_TOKEN) return
2020-07-14 17:00:58 +02:00
posthog.init(process.env.POSTHOG_TOKEN, {
api_host: process.env.POSTHOG_URL,
})
posthog.set_config({ persistence: "cookie" })
2020-07-14 17:00:58 +02:00
}
function identify(id) {
if (!analyticsEnabled) return
if (!id) return
posthog.identify(id)
Sentry.configureScope(scope => {
scope.setUser({ id: id })
})
}
async function identifyByApiKey(apiKey) {
if (!analyticsEnabled) return true
const response = await fetch(
`https://03gaine137.execute-api.eu-west-1.amazonaws.com/prod/account/id?api_key=${apiKey.trim()}`
)
if (response.status === 200) {
const id = await response.json()
await api.put("/api/keys/userId", { value: id })
identify(id)
return true
}
return false
}
2020-07-14 17:00:58 +02:00
function captureException(err) {
if (!analyticsEnabled) return
2020-07-14 17:00:58 +02:00
Sentry.captureException(err)
}
function captureEvent(eventName, props = {}) {
if (!analyticsEnabled || !process.env.POSTHOG_TOKEN) return
props.sourceApp = "builder"
posthog.capture(eventName, props)
}
2020-07-14 17:00:58 +02:00
export default {
activate,
identify,
identifyByApiKey,
2020-07-14 17:00:58 +02:00
captureException,
2020-07-16 16:19:46 +02:00
captureEvent,
2020-07-14 17:00:58 +02:00
}