UNPKG

x-http-client

Version:

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

69 lines (58 loc) 1.86 kB
var isFunction = require('x-common-utils/isFunction'); var isAbsoluteURL = require('x-common-utils/isAbsoluteURL'); var isPlainObject = require('x-common-utils/isPlainObject'); /** * The function to build request url. * * 1. Add baseURL if needed. * 2. Compile url if needed. * 3. Compile query string if needed. * * @param {RequestOptions} options The request options. * @returns {string} Returns the final url string. */ function buildURL(options) { var url = options.url; var baseURL = options.baseURL; var model = options.model; var query = options.query; var compileURL = options.compileURL; var encodeQueryString = options.encodeQueryString; var array; if (url === null || url === undefined) { url = ''; } // make sure that url is a string. url = '' + url; // If the url is not absolute url and the baseURL is defined, // prepend the baseURL to the url. if (!isAbsoluteURL(url)) { if (baseURL === null || baseURL === undefined) { baseURL = ''; } url = baseURL + url; } // Compile the url if needed. if (isPlainObject(model) && isFunction(compileURL)) { url = compileURL(url, model, options); } // Compile the query string. if (isPlainObject(query) && isFunction(encodeQueryString)) { query = encodeQueryString(query, options); array = url.split('#'); // There may be hash string in the url. url = array[0]; if (url.indexOf('?') > -1) { if (url.charAt(url.length - 1) === '&') { url = url + query; } else { url = url + '&' + query; } } else { url = url + '?' + query; } array[0] = url; url = array.join('#'); } return url; } module.exports = buildURL;