/
index.js
106 lines (89 loc) · 3.04 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*global window */
/*global $ */
/*jslint node: true */
/*global exports */
/*global require */
/*global confirm */
/*global alert */
/*global ga */
var utils = require('tsuju-utils');
var events = require('events');
var node = (typeof window === 'undefined');
module.exports = function(trackingId, opts) {
"use strict";
utils.is.string(trackingId, 'trackingId');
var that = new events.EventEmitter();
var log = utils.log(that);
opts = opts || {};
var uuid = opts.uuid || utils.uuid();
var appName = opts.appName || 'none';
var appVersion = opts.appVersion || 'none';
var params = {};
var visitor;
that.setDimension = function setDimension(dimensionName, dimensionValue) {
ga('set', dimensionName, dimensionValue);
};
if (node) {
var ua = require('universal-analytics');
visitor = ua(trackingId);
params.an = appName;
params.av = appVersion;
} else {
ga('create', trackingId, {
'storage': 'none',
'clientId': uuid,
'siteSpeedSampleRate': 100
});
that.setDimension('dimension1', appVersion);
}
that.captureErrors = function(fromLog, then) {
var oldError = fromLog.error;
fromLog.error = function newError(error, path) {
oldError.apply(this, arguments);
if (path) {
error.path = path;
}
that.error(error, function() {
then(error);
});
};
};
that.event = function send(category, action, label, value, callback) {
log('sending to ' + trackingId + ", " + category + ", " + action + ", " + label + ", " + value);
if (node) {
visitor.event(category, action, label, value, params, function(error) {
if (error) {
log.warn('failed to send ga to ' + trackingId);
log.error(error);
} else {
log.info('sent ga to ' + trackingId + ", " + category + ", " + action + ", " + label + ", " + value);
}
if (callback) {
callback();
}
});
} else {
if (ga) {
ga('send', 'event', category, action, label, value);
log.info('sent ga to ' + trackingId + ", " + category + ", " + action + ", " + label + ", " + value);
if (callback) {
callback();
}
}
}
};
that.pageView = function pageView(page, title, queryString) {
log.info('pageView: ' + trackingId + ", " + page + ", " + title);
that.setDimension('dimension2', queryString);
ga('send', 'pageview', {
'page': page,
'title': title
});
};
that.error = function error(err, callback) {
var message = err.message || '(no message)';
var path = err.path || '(no path)';
that.event('error', message, JSON.stringify(err), null, callback);
};
return that;
};