Skip to content

Instantly share code, notes, and snippets.

@Tuch
Created December 8, 2020 10:32
Show Gist options
  • Save Tuch/d0884323bd004fa0e64922e6fa0a24fa to your computer and use it in GitHub Desktop.
Save Tuch/d0884323bd004fa0e64922e6fa0a24fa to your computer and use it in GitHub Desktop.
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