Created
December 25, 2020 15:49
-
-
Save radzionc/3b9a758e277a0d28a015495a51df18ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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