Skip to content

Instantly share code, notes, and snippets.

@jchris
Created January 8, 2014 00:11
Show Gist options
  • Save jchris/8309308 to your computer and use it in GitHub Desktop.
Save jchris/8309308 to your computer and use it in GitHub Desktop.
/*
* hoax
* https://github.com/jchris/hoax
*
* Copyright (c) 2013 Chris Anderson
* Licensed under the Apache license.
*/
module.exports = function(request) {
var pax = require("pax");
function makeHoaxCallback(cb, reqOpts) {
return function(err, res, body){
console.log("request complete", err, reqOpts);
if (err && err !== "error") {
cb(err, res, body);
} else {
if (res.statusCode >= 400 || err === "error") {
cb(body || res.statusCode, res);
} else {
cb(null, body);
}
}
};
}
function processArguments(myPax, urlOrOpts, data, cb, verb) {
var opts = {}, newPax = myPax;
if (typeof urlOrOpts === 'function') {
cb = urlOrOpts;
data = null;
urlOrOpts = null;
} else {
if (urlOrOpts.uri || urlOrOpts.url) {
newPax = myPax(urlOrOpts.uri || urlOrOpts.url);
} else {
if (typeof data === 'function') {
// we have only 2 args
// the first is data if it is not an array
// and the verb is put or post
cb = data;
data = null;
if ((verb === "put" || verb === "post") &&
(typeof urlOrOpts !== "string" &&
Object.prototype.toString.call(urlOrOpts) !== '[object Array]')) {
data = urlOrOpts;
} else {
newPax = myPax(urlOrOpts);
}
} else {
newPax = myPax(urlOrOpts);
}
}
}
opts.headers = {'content-type': 'application/json'};
opts.json = true;
opts.uri = newPax.toString();
if (data) {
opts.body = JSON.stringify(data);
}
return [opts, cb, newPax];
}
function extenderizer(oldHoax) {
return function(name, fun) {
this.methods = this.methods || {};
this.methods[name] = fun;
this[name] = fun;
};
}
function addExtensions(newHoax, oldHoax) {
if (oldHoax && oldHoax.methods) {
var k;
for (k in oldHoax.methods) {
newHoax[k] = oldHoax.methods[k];
}
}
}
function makeHoax(myPax, verb, oldHoax) {
var newHoax = function(opts, data, xcb) {
var args = processArguments(myPax, opts, data, xcb, verb),
reqOpts = args[0], // includes uri, body
cb = args[1],
newPax = args[2];
if (cb) {
// console.log(["hoax", verb||"get", reqOpts]);
if (verb) {
return request[verb](reqOpts, makeHoaxCallback(cb, reqOpts));
} else {
return request(reqOpts, makeHoaxCallback(cb, reqOpts));
}
} else {
// console.log("new hoax", newPax);
return makeHoax(newPax, verb, newHoax);
}
};
if (!verb) {
"get put post head del".split(" ").forEach(function(v){
newHoax[v] = makeHoax(myPax, v, newHoax);
});
}
addExtensions(newHoax, oldHoax);
// should this be extenderizer(newHoax) ?
newHoax.extend = extenderizer(oldHoax);
newHoax.pax = myPax;
return newHoax;
}
var Hoax = makeHoax(pax());
Hoax.makeHoax = makeHoax;
return Hoax;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment