request-json
Version:
HTTP client for very simple usages and JSON requests only
110 lines (94 loc) • 2.86 kB
JavaScript
// Generated by CoffeeScript 1.3.3
(function() {
var fs, parseBody, request;
request = require("request");
fs = require("fs");
parseBody = function(error, response, body, callback) {
try {
if (typeof body === "string") {
body = JSON.parse(body);
}
return callback(error, response, body);
} catch (err) {
return callback(err, response, body);
}
};
exports.JsonClient = (function() {
function JsonClient(host) {
this.host = host;
}
JsonClient.prototype.setBasicAuth = function(username, password) {
var basicCredentials, credentials;
credentials = "" + username + ":" + password;
basicCredentials = new Buffer(credentials).toString('base64');
return this.auth = "Basic " + basicCredentials;
};
JsonClient.prototype.get = function(path, callback) {
return request({
method: 'GET',
headers: {
accept: 'application/json',
authorization: this.auth
},
uri: this.host + path
}, function(error, response, body) {
return parseBody(error, response, body, callback);
});
};
JsonClient.prototype.post = function(path, json, callback) {
return request({
method: "POST",
uri: this.host + path,
json: json,
headers: {
authorization: this.auth
}
}, function(error, response, body) {
return parseBody(error, response, body, callback);
});
};
JsonClient.prototype.put = function(path, json, callback) {
return request({
method: "PUT",
uri: this.host + path,
json: json,
headers: {
authorization: this.auth
}
}, function(error, response, body) {
return parseBody(error, response, body, callback);
});
};
JsonClient.prototype.del = function(path, callback) {
return request({
method: "DELETE",
uri: this.host + path,
headers: {
authorization: this.auth
}
}, function(error, response, body) {
return parseBody(error, response, body, callback);
});
};
JsonClient.prototype.sendFile = function(path, filePath, data, callback) {
var att, form, req;
if (typeof data === "function") {
callback = data;
}
req = this.post(path, null, callback);
form = req.form();
if (typeof data !== "function") {
for (att in data) {
form.append(att, data[att]);
}
}
return form.append('file', fs.createReadStream(filePath));
};
JsonClient.prototype.saveFile = function(path, filePath, callback) {
var stream;
stream = this.get(path, callback);
return stream.pipe(fs.createWriteStream(filePath));
};
return JsonClient;
})();
}).call(this);