Created
December 8, 2020 10:32
-
-
Save Tuch/d0884323bd004fa0e64922e6fa0a24fa to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { stringify } from 'qs'; | |
import { isObject } from 'lodash/fp'; | |
import { nanoid } from 'nanoid'; | |
const url = '/a/track-envent'; | |
const CID_KEY = '_acid'; | |
export const createAnalytics = ({ apiOrigin }) => { | |
let context = {}; | |
const getCid = () => { | |
let cid = null; | |
if (global.sessionStorage) { | |
cid = global.sessionStorage.getItem(CID_KEY); | |
if (!cid) { | |
cid = nanoid(); | |
global.sessionStorage.setItem(CID_KEY, cid); | |
} | |
} | |
return cid; | |
}; | |
const trackEvent = ({ v1, v2, v3, v4 }) => { | |
const image = new Image(); | |
const c = getCid(); | |
const searchString = stringify( | |
{ ...context, c, v1, v2, v3, v4, r: Math.random() }, | |
{ addQueryPrefix: true }, | |
); | |
image.src = `${apiOrigin}${url}${searchString}`; | |
}; | |
const setContext = (_context = {}) => { | |
if (!isObject(_context)) { | |
throw new Error('My analytics context should be an object!'); | |
} | |
context = _context; | |
}; | |
return { setContext, getCid, trackEvent }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment