-
-
Save cancerberoSgx/491700fddfd273111ecef7eb75d477dd to your computer and use it in GitHub Desktop.
Promisified Hyperquest -- A quick exercise wrapping Hyperquest in a Promise for an easy thenable API.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var concat = require("concat-stream"); | |
var hyperquest = require("hyperquest"); | |
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment