Created
March 27, 2017 10:42
-
-
Save KagamiChan/b7547d33eee1f647da6e46d85b40e6de to your computer and use it in GitHub Desktop.
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
// code modified from https://github.com/petkaantonov/bluebird/issues/196 | |
import http from 'http' | |
import https from 'https' | |
import Promise from 'bluebird' | |
import streamBuffers from 'stream-buffers' | |
const promiseRequest = Promise.method(options => new Promise((resolve, reject) => { | |
const scheme = options.scheme || 'http' | |
let handler | |
switch (scheme) { | |
case 'http': | |
handler = http | |
break | |
case 'https': | |
handler = https | |
break | |
default: | |
handler = http | |
} | |
const request = handler.request(options, (response) => { | |
// Bundle the result | |
const result = { | |
httpVersion: response.httpVersion, | |
httpStatusCode: response.statusCode, | |
headers: response.headers, | |
body: new streamBuffers.WritableStreamBuffer(), | |
trailers: response.trailers, | |
} | |
// Build the body | |
response.on('data', (chunk) => { | |
result.body.write(chunk) | |
}) | |
// Resolve the promise when the response ends | |
response.on('end', () => { | |
resolve([result, result.body.getContents()]) | |
}) | |
}) | |
// Handle errors | |
request.on('error', (error) => { | |
console.log('Problem with request:', error.message) | |
reject(error) | |
}) | |
// Must always call .end() even if there is no data being written to the request body | |
request.end() | |
})) | |
export default promiseRequest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment