Last active
August 29, 2015 14:24
-
-
Save jdx/3d61faf33e8cee99420b to your computer and use it in GitHub Desktop.
simple node json http request function with promises and no dependencies
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
'use strict'; | |
let http = require('http'); | |
let https = require('https'); | |
let parseUrl = require('url').parse; | |
function concat (stream, callback) { | |
var strings = []; | |
stream.on('data', function (data) { | |
strings.push(data); | |
}); | |
stream.on('end', function () { | |
callback(strings.join('')); | |
}); | |
} | |
function request (method, url, payload) { | |
return new Promise(function (fulfill, reject) { | |
url = parseUrl(url); | |
let req = (url.protocol === 'https:' ? https : http).request({ | |
hostname: url.hostname, | |
path: url.path, | |
method: method | |
}, function (res) { | |
concat(res, function (data) { | |
if (res.statusCode >= 200 && res.statusCode < 300) fulfill(data); | |
else reject(data); | |
}); | |
}); | |
req.on('error', reject); | |
if (payload) { | |
let body = JSON.stringify(payload); | |
req.setHeader('Content-Length', Buffer.byteLength(body)); | |
req.write(body); | |
} | |
req.end(); | |
}); | |
} | |
module.exports = request; | |
module.exports.get = function (url, payload) { request('GET', url, payload); }; | |
module.exports.post = function (url, payload) { request('POST', url, payload); }; | |
module.exports.put = function (url, payload) { request('PUT', url, payload); }; | |
module.exports.patch = function (url, payload) { request('PATCH', url, payload); }; | |
module.exports.delete = function (url, payload) { request('DELETE', url, payload); }; | |
request('POST', 'https://api.myapp.com', {foo: 'bar'}); | |
request('GET', 'https://www.google.com').then(function (body) { | |
console.log(body); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment