2
\$\begingroup\$

The Node.JS HTTP and HTTPS modules only provide .get shortcut function, unlike AngularJS's $http which provides them all. I went about creating a function that returns one of these shortcut functions:

'use strict';

var http = require('http');

function httpF(method) {
    return function (options, body_or_cb, cb) {
        if (!cb) {
            cb = body_or_cb;
            body_or_cb = null;
        }
        options['method'] = method;
        if (body_or_cb)
            if (!options)
                options = {'headers': {'Content-Length': Buffer.byteLength(body_or_cb)}};
            else if (!options.headers)
                options.headers = {'Content-Length': Buffer.byteLength(body_or_cb)};
            else if (!options.headers['Content-Length'])
                options.headers['Content-Length'] = Buffer.byteLength(body_or_cb);
        var req = http.request(options, function (res) {
            if (!res)
                return cb(res);
            else if ((res.statusCode / 100 | 0) > 3)
                return cb(res);
            return cb(null, res);
        });
        body_or_cb && req.write(body_or_cb);
        req.end();
        return req;
    };
}

It pushes the callback through an (err, res) signature also. The idea here is to enable chaining in async.js or use as a Bluebird promise.

Usage:

var httpPOST = httpF('POST');

httpPOST({
    protocol: 'http:',
    host: 'httpbin.org',
    path: '/post',
    headers: {'Content-Type': 'application/json'}
}, JSON.stringify({hello: 'world'}), function (err, res) {
    if (err)
        console.error(err.statusCode, err.statusMessage);
    else
        console.info(res.statusCode, res.statusMessage);
});

Original TypeScript

Some improvement ideas:

  • Use url.parse to enable httpPOST('https://httpbin.org/post', .. (including use of https module)
  • Wrap all errors up into something util.inherits from Error
  • Fix bug that stops async.series from continuing after failure (even happens with this hack e ? cb() : cb(null, r))

I also submitted this as a PR, but it was rejected (as expected).

\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to Code Review! You mentioned a bug towards the end, does your code actually work as intended? \$\endgroup\$ – Phrancis Apr 2 '16 at 2:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.