-
-
Save lpirola/5dfbc7ce428b13faf06aa46cad6d63a3 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 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