appadhoc
Version:
AppAdhoc module for A/B testing
117 lines (97 loc) • 2.62 kB
JavaScript
// Only three calls are public to user app:
// init(adhoc_app_track_id)
// generateClientId()
// getExperimentFlags(client_id, callback)
// incrementStat(client_id, stat, value)
//
// @client_id: unique ID to identify a user, preferrably a UUID.
var protocol = "https:";
var ADHOC_GETFLAGS_HOST = 'experiment.appadhoc.com';
var ADHOC_GETFLAGS_PORT = '80';
var ADHOC_GETFLAGS_PATH = '/get_flags';
var ADHOC_TRACKING_HOST = 'tracker.appadhoc.com';
var ADHOC_TRACKING_PORT = '80';
var ADHOC_TRACKING_PATH = '/tracker';
var ADHOC_FORCEEXP_HOST = 'experiment.appadhoc.com';
var ADHOC_FORCEEXP_PORT = '80';
var ADHOC_FORCEEXP_PATH = '/force_clients';
var http = require("http");
//var cache = require("node-cache");
// Canonicalize Date.now().
if (!Date.now) {
Date.now = function() {
return new Date().getTime();
};
}
// Micro implementaiton of AJAX.
function AJAX(host, port, path, query, callback) {
var request = http.request(
{
host: host,
port: port,
path: path,
method: 'POST',
headers: {
'Content-Type' : 'application/json;charset=UTF-8'
}
},
function(response) {
if (callback == null) {
return;
}
var reply = '';
response.on('data', function(chunk) {
reply += chunk;
});
response.on('end', function() {
callback(reply);
});
}
);
request.write(JSON.stringify(query));
request.end();
};
var adhoc = module.exports;
adhoc.opts = {};
adhoc.init = function(appKey) {
adhoc.ak = appKey; // ak as appKey
};
adhoc.generateClientId = function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
};
adhoc.getExperimentFlags = function(client_id, callback) {
var data = {
app_key: adhoc.ak,
event_type: 'GET_EXPERIMENT_FLAGS',
summary: {},
client_id: client_id,
custom: adhoc.opts
}
AJAX(ADHOC_GETFLAGS_HOST, ADHOC_GETFLAGS_PORT, ADHOC_GETFLAGS_PATH, data, callback);
};
adhoc.incrementStat = function(client_id, stat, value) {
var data = {
app_key: adhoc.ak,
client_id: client_id,
summary: {},
stats: [{
key : stat,
value : value,
timestamp : Math.round(Date.now() / 1000)
}]
};
AJAX(ADHOC_TRACKING_HOST, ADHOC_TRACKING_PORT, ADHOC_TRACKING_PATH, data, function(){});
};
adhoc.forceExperiment = function(client_id,qr_code){
var data = {
client_id: client_id,
qr_code: qr_code
};
AJAX(ADHOC_FORCEEXP_HOST, ADHOC_FORCEEXP_PORT, ADHOC_FORCEEXP_PATH, data, function(){});
}
adhoc.setProperties = function(opts){
adhoc.opts = opts;
}