Skip to content

Instantly share code, notes, and snippets.

@radzionc
Created December 25, 2020 15:49
Show Gist options
  • Save radzionc/3b9a758e277a0d28a015495a51df18ea to your computer and use it in GitHub Desktop.
Save radzionc/3b9a758e277a0d28a015495a51df18ea to your computer and use it in GitHub Desktop.
import * as Sentry from '@sentry/browser'
import * as Amplitude from 'amplitude-js'
import { PATH } from '../constants/routing'
import { isEbmeddedLanding } from './routing'
import { reportError } from './reporting'
const trackEvent = name => {
try {
Amplitude.getInstance().logEvent(name)
} catch (err) {
reportError('Fail to track event with Amplitude', { name }, err)
}
try {
window.smartlook && window.smartlook('track', name)
} catch (err) {
reportError('SmartLook: fail to track event', { name }, err)
}
}
class Analytics {
constructor() {
try {
Amplitude.getInstance().init(
process.env.REACT_APP_AMPLITUDE_API_KEY,
null,
{
includeReferrer: true,
disableCookies: true
}
)
} catch (err) {
reportError('Fail to initialize Amplitude', null, err)
}
}
pageview() {
const path = Object.keys(PATH).find(
p => PATH[p] === window.location.pathname
)
if (path) {
trackEvent(`Visit ${path}`)
}
}
setUser(userId, name) {
try {
Amplitude.getInstance().setUserId(userId)
Amplitude.getInstance().setUserProperties({ name })
} catch (err) {
reportError('Heap: fail to set user', { userId, name }, err)
}
try {
window.smartlook && window.smartlook('identify', userId, { name })
} catch (err) {
reportError('Smartlook: fail to set user', { userId, name }, err)
}
}
}
let analytics
/**
* @returns {Analytics}
*/
export const getAnalytics = () => {
if (!analytics) {
if (process.env.NODE_ENV === 'production' && !isEbmeddedLanding()) {
analytics = new Analytics()
} else {
analytics = Object.getOwnPropertyNames(Analytics.prototype).reduce(
(acc, key) => ({
...acc,
[key]: () => ({})
}),
{}
)
analytics.getVideoAnalytics = () => ({
play: () => ({}),
close: () => ({}),
finish: () => ({})
})
}
}
return analytics
}
export const setUserForReporting = (id, name) => {
if (process.env.NODE_ENV === 'production') {
Sentry.configureScope(scope => {
scope.setUser({ id })
})
getAnalytics().setUser(id, name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment