x-http-client
Version:
An http client to make it easier to send requests (including JSONP requests) to the server.
61 lines (52 loc) • 1.7 kB
JavaScript
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 the url is not absolute url and the baseURL is defined,
// prepend the baseURL to the url.
if (!isAbsoluteURL(url)) {
if (typeof baseURL === 'string') {
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;