Skip to content

Instantly share code, notes, and snippets.

@lpirola
Forked from nioufe/track.js
Created March 28, 2017 01:56
Show Gist options
  • Save lpirola/5dfbc7ce428b13faf06aa46cad6d63a3 to your computer and use it in GitHub Desktop.
Save lpirola/5dfbc7ce428b13faf06aa46cad6d63a3 to your computer and use it in GitHub Desktop.
import LogmaticJs from 'logmatic-js';
const track = function (verb) {
// Event fields
const _verb = verb;
let _object = null;
let _target = null;
let _start = null;
// The builder
const t = {};
// Start timing the event
t.timed = () => {
_start = new Date();
return t;
};
// Define object
t.of = (type, id, content) => {
if (type != null) {
_object = { objectType: type };
if (id != null) {
_object.id = id;
}
if (content != null) {
_object.content = content;
}
}
return t;
};
// Define target
t.on = (type, id, content) => {
if (type != null) {
_target = { objectType: type };
if (id != null) {
_target.id = id;
}
if (content != null) {
_target.content = content;
}
}
return t;
};
// Emit the event
t.emit = () => {
const msg = [ _verb ];
const payload = {
verb: _verb
};
if (_object != null) {
msg.push(_object.objectType);
if (_object.content || _object.id) {
msg.push(JSON.stringify(_object.content || _object.id));
}
payload.object = _object;
}
if (_target != null) {
msg.push('on', _target.objectType);
if (_target.content || _target.id) {
msg.push(JSON.stringify(_target.content || _target.id));
}
payload.target = _target;
}
if (_start != null) {
const duration = new Date().getTime() - _start.getTime();
msg.push('took', duration, 'ms');
payload.took = duration;
}
logmaticJs.log(msg.join(' '), payload);
};
return t;
};
export default track;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment