insomnia/app/backend/analytics.js

52 lines
1.2 KiB
JavaScript
Raw Normal View History

2016-09-21 00:03:26 +00:00
'use strict';
const Analytics = require('analytics-node');
const {getAppVersion} = require('./appInfo');
const db = require('./database');
const {SEGMENT_WRITE_KEY} = require('./constants');
let analytics = null;
let userId = null;
2016-09-21 00:03:26 +00:00
module.exports.initAnalytics = () => {
return new Promise((resolve, reject) => {
analytics = new Analytics(SEGMENT_WRITE_KEY);
if (!userId) {
2016-09-21 20:49:54 +00:00
return db.stats.get().then(stats => {
userId = stats._id;
// Recurse now that we have a userId
2016-09-21 00:03:26 +00:00
return module.exports.initAnalytics();
}).then(resolve, reject);
}
analytics.identify({
userId,
traits: {
appPlatform: process.platform,
appVersion: getAppVersion(),
// Reserved Traits
createdAt: new Date()
}
});
console.log(`-- Analytics Initialized for ${userId} --`);
resolve();
});
2016-09-21 00:03:26 +00:00
};
2016-09-21 00:03:26 +00:00
module.exports.trackEvent = (event, properties = {}) => {
// Don't track events if we haven't set them up yet
if (analytics) {
2016-09-13 18:46:51 +00:00
// Add base properties
Object.assign(properties, {
appPlatform: process.platform,
appVersion: getAppVersion()
});
analytics.track({userId, event, properties});
}
2016-09-21 00:03:26 +00:00
};