function json()

in apps/mountebank-mock/mountebank-source/src/util/middleware.js [187:220]


function json (log) {
    return function (request, response, next) {
        // Disable body parsing, if already parsed
        if (request.headers['content-type'] === 'application/json' && helpers.isObject(request.body)) {
            next();
            return;
        }

        request.body = '';
        request.setEncoding('utf8');
        request.on('data', chunk => {
            request.body += chunk;
        });
        request.on('end', function () {
            if (request.body === '') {
                next();
            }
            else {
                try {
                    request.body = JSON.parse(request.body);
                    request.headers['content-type'] = 'application/json';
                    next();
                }
                catch (e) {
                    log.error('Invalid JSON: ' + request.body);
                    response.statusCode = 400;
                    response.send({
                        errors: [errors.InvalidJSONError({ source: request.body })]
                    });
                }
            }
        });
    };
}