Skip to content

Instantly share code, notes, and snippets.

@nikcorg
Last active May 10, 2018 05:44
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nikcorg/0999f547a32299e44fef to your computer and use it in GitHub Desktop.
Save nikcorg/0999f547a32299e44fef to your computer and use it in GitHub Desktop.
Promisified Hyperquest -- A quick exercise wrapping Hyperquest in a Promise for an easy thenable API.
var concat = require("concat-stream");
var hyperquest = require("hyperquest");
var Promise = require("bluebird");
var stream = require("stream");
// Wait for the request to finish or fail
function promisify(req) {
return new Promise(function (resolve, reject) {
req.on("error", reject).pipe(concat({ encoding: "string" }, resolve));
});
}
// Prepare the request object
function send(method, url, options, payload) {
options = options || {};
options.method = method;
options.headers = options.headers || {};
return new Promise(function (resolve, reject) {
var req = hyperquest(url, options);
// Send the payload down the wire, if present and applicable
if (payload && req.writable && payload instanceof stream.Readable) {
payload.pipe(req);
} else if (payload && req.writable) {
if (typeof payload != "string") {
req.end();
return reject(new Error("Payload must be a stream or a string"));
}
options.headers["content-length"] = Buffer.byteLength(payload, "utf-8") || 0;
req.write(payload);
} else if (req.writable) {
req.write(null);
}
// Wrap the response and error in a blanket of information
promisify(req).
then(function (data) {
resolve({
data: data,
error: null,
options: options,
request: req.request,
response: req.response
});
}, function (err) {
reject({
data: null,
error: err,
options: options,
request: req.request,
response: req.response
});
});
});
}
// Generate shorthand methods for http verbs
["get", "put", "post", "delete", "patch", "head"].forEach(function (method) {
send[method] = function (url, options, payload) {
return send(method, url, options, payload);
};
});
module.exports = send;
@cancerberoSgx
Copy link

this is good, I know is simple, but I think publishing this in npm would be helpful. Will you? can I ? thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment