UNPKG

x-http-client

Version:

An http client to simplify sending requests (HTTP & JSONP) in the browser.

74 lines (65 loc) 2.39 kB
var merge = require('x-common-utils/merge'); var isFunction = require('x-common-utils/isFunction'); var isPlainObject = require('x-common-utils/isPlainObject'); var hasOwn = require('../shared/hasOwn'); /** * Find a processor from `options.httpRequestBodyProcessor` to process the request body. * * @param {RequestOptions} options The request options. * @returns {any} Retruns the content that send to the server. */ function handleRequestBody(options) { var i; var l; var key; var content = null; var processor; var contentProcessor; var contentProcessors = []; var body = options.body; var processors = options.httpRequestBodyProcessor; var headers = isPlainObject(options.headers) ? options.headers : {}; if (isPlainObject(body) && isPlainObject(processors)) { // Find all processors. for (key in processors) { if (hasOwn.call(processors, key)) { processor = processors[key]; if (isPlainObject(processor)) { contentProcessors.push({ key: key, headers: processor.headers, priority: processor.priority, processor: processor.processor }); } } } // Sort the processors by its priority. contentProcessors.sort(function (a, b) { return b.priority - a.priority; }); // Find the first non-undefined content. for (i = 0, l = contentProcessors.length; i < l; i += 1) { processor = contentProcessors[i]; if (body[processor.key] !== undefined) { content = body[processor.key]; contentProcessor = processor; break; } } // Use the processor to process the content. if (contentProcessor) { if (isPlainObject(contentProcessor.headers)) { headers = merge({}, contentProcessor.headers, headers); } processor = contentProcessor.processor; if (isFunction(processor)) { content = processor(content, options); } } } // Make sure that the headers is a plain object. options.headers = headers; return content; } module.exports = handleRequestBody;