Skip to content

Instantly share code, notes, and snippets.

@ericlathrop
Created July 29, 2015 18:23
Show Gist options
  • Save ericlathrop/f546070ccca088b84597 to your computer and use it in GitHub Desktop.
Save ericlathrop/f546070ccca088b84597 to your computer and use it in GitHub Desktop.
"use strict";
var http = require("http");
function HttpError(statusCode) {
this.name = "HttpError";
this.statusCode = statusCode;
this.message = "Recieved status code " + statusCode;
}
HttpError.prototype = Error.prototype;
function request(method, path, data, callback) {
var req = http.request({ method: method, path: path }, function(res) {
var resData = "";
if (res.statusCode >= 400) {
callback(new HttpError(res.statusCode));
return;
}
res.on("data", function(buf) {
resData += buf;
});
res.on("error", function(err) {
callback(err);
});
res.on("end", function() {
callback(undefined, resData);
});
});
if (data !== undefined) {
req.write(data);
}
req.end();
}
function get(path, callback) {
request("GET", path, undefined, callback);
}
function put(path, data, callback) {
request("PUT", path, data, callback);
}
function getJson(path, callback) {
get(path, function(err, data) {
if (err) {
callback(err);
return;
}
callback(undefined, JSON.parse(data));
});
}
function putJson(path, data, callback) {
put(path, JSON.stringify(data), function(err, resData) {
if (err) {
callback(err);
return;
}
callback(undefined, JSON.parse(resData));
});
}
module.exports = {
get: get,
getJson: getJson,
put: put,
putJson: putJson
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment