Skip to content

Instantly share code, notes, and snippets.

@mayorbyrne
Created December 19, 2014 21:27
Show Gist options
  • Save mayorbyrne/097ef137b499c7ec44bc to your computer and use it in GitHub Desktop.
Save mayorbyrne/097ef137b499c7ec44bc to your computer and use it in GitHub Desktop.
var BB = require('bluebird');
var request = BB.promisifyAll(require('request'));
var ziptoo = require('funkit').functional.ziptoo;
var resourcesToKey = {
'checks' : function(obj){
return obj.checks || obj.check;
},
'analysis' : function(obj) {
return obj.analysis || obj;
},
'reference': function(obj){
return obj;
},
'reports.email': function(obj){
return obj.subscriptions;
},
'reports.shared': function(obj){
return obj.shared.banners;
},
'single': function(obj){
return obj.result;
}
};
function init(config) {
// https://www.pingdom.com/services/api-documentation-rest/
var baseUrl = 'https://api.pingdom.com/api/2.0/';
var resources = ['actions', 'analysis', 'checks', 'contacts', 'credits', 'probes',
'reference', 'reports.email', 'reports.public', 'reports.shared',
'results', 'servertime', 'settings', 'summary.average', 'summary.hoursofday',
'summary.outage', 'summary.performance', 'summary.probes', 'single', 'traceroute'
];
return ziptoo(resources.map(function(resource) {
return [resource, template.bind(undefined, config, baseUrl, resource)];
}));
}
module.exports = init;
function template(config, baseUrl, property, cb, o) {
o = o || {};
var method = (o.method || 'get') + 'Async';
var target = o.target || '';
var qs = o.qs || {};
// accept Date objects and convert them to Unix format here
if(qs.to) qs.to = dateToUnix(qs.to);
if(qs.from) qs.from = dateToUnix(qs.from);
return request[method](baseUrl + property + '/' + target, {
auth: config,
headers: {
'App-Key': config.appkey
},
qs: qs
})
.spread(function(res, body){
obj = JSON.parse(body);
if(obj.error) {
return BB.reject(obj.error);
}
if(typeof resourcesToKey[property] !== 'undefined'){
data = resourcesToKey[property](obj);
} else {
data = JSON.parse(res.body)[property.split('.')[1]] || JSON.parse(res.body)[property.split('.')[0]];
}
return [data, res];
})
.nodeify(cb, {
spread: true
});
}
function dateToUnix(date) {
return parseInt(date.getTime() / 1000, 10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment