serverless/lib/utils/userStats.js
2019-07-18 20:32:03 +02:00

80 lines
2.2 KiB
JavaScript

'use strict';
const { format } = require('util');
const BbPromise = require('bluebird');
const _ = require('lodash');
const fetch = require('node-fetch');
const configUtils = require('./config');
const isTrackingDisabled = require('./isTrackingDisabled');
const isValidEventName = require('./userStatsValidation');
const log = require('./log/serverlessLog');
const TRACKING_IS_DISABLED = isTrackingDisabled();
const TRACK_URL = 'https://serverless.com/api/framework/track';
const logError = (type, error) => {
if (!process.env.SLS_DEBUG) return;
log(format('User stats error: %s: %O', type, error));
};
/* note tracking swallows errors */
function request(url, payload) {
return fetch(url, {
method: 'POST',
// set to 1000 b/c no response needed
timeout: 1000,
body: JSON.stringify(payload),
}).then(
response => {
if (response.status < 200 || response.status >= 300) {
logError('Unexpected response', response);
}
},
networkError => logError('Network error', networkError)
);
}
function track(eventName, payload) {
return BbPromise.try(() => {
const data = payload || {};
let userId = data.id;
let userEmail = data.email;
// exit early if tracking disabled
if (TRACKING_IS_DISABLED && !data.force) return null;
const config = configUtils.getConfig();
const frameworkId = config.frameworkId;
// getConfig for values if not provided from .track call
if (!userId || !userEmail) {
userId = config.userId;
if (config.users && config.users[userId] && config.users[userId].email) {
userEmail = config.users[userId].email;
}
}
// automatically add `framework:` prefix
if (eventName.indexOf('framework:') === -1) eventName = `framework:${eventName}`;
// to ensure clean data, validate event name
if (!isValidEventName(eventName)) return null;
const defaultData = {
event: eventName,
id: userId,
frameworkId,
email: userEmail,
data: {
id: userId,
timestamp: Math.round(+new Date() / 1000),
},
};
delete data.force;
const eventData = _.merge(defaultData, data);
return request(TRACK_URL, eventData);
});
}
module.exports = { track };