aboutsummaryrefslogtreecommitdiff
path: root/lib/restreamer.js
blob: 00b5aa9bd8eb024456e5df875640d16b273d54ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Adapted from connect-restreamer, with bugfix to move "next" after the process.nextTick()
module.exports = function (options) {
    options = options || {};
    options.property = options.property || 'body';
    options.stringify = options.stringify || JSON.stringify;

    return function (req, res, next) {
        req.removeAllListeners('data');
        req.removeAllListeners('end');
        if (req.headers['content-length'] !== undefined) {
            req.headers['content-length'] = Buffer.byteLength(options.stringify(req[options.property]), 'utf8');
        }
        process.nextTick(function () {
            if (req[options.property]) {
                if ('function' === typeof options.modify)
                    req[options.property] = options.modify(req[options.property]);
                req.emit('data', options.stringify(req[options.property]));
            }
            req.emit('end');
        });
        next();
    };
};