UNPKG

1.86 kBJavaScriptView Raw
1var isFunction = require('x-common-utils/isFunction');
2var isAbsoluteURL = require('x-common-utils/isAbsoluteURL');
3var isPlainObject = require('x-common-utils/isPlainObject');
4
5/**
6 * The function to build request url.
7 *
8 * 1. Add baseURL if needed.
9 * 2. Compile url if needed.
10 * 3. Compile query string if needed.
11 *
12 * @param {RequestOptions} options The request options.
13 * @returns {string} Returns the final url string.
14 */
15function buildURL(options) {
16 var url = options.url;
17 var baseURL = options.baseURL;
18 var model = options.model;
19 var query = options.query;
20 var compileURL = options.compileURL;
21 var encodeQueryString = options.encodeQueryString;
22 var array;
23
24 if (url === null || url === undefined) {
25 url = '';
26 }
27
28 // make sure that url is a string.
29 url = '' + url;
30
31 // If the url is not absolute url and the baseURL is defined,
32 // prepend the baseURL to the url.
33 if (!isAbsoluteURL(url)) {
34 if (baseURL === null || baseURL === undefined) {
35 baseURL = '';
36 }
37 url = baseURL + url;
38 }
39
40 // Compile the url if needed.
41 if (isPlainObject(model) && isFunction(compileURL)) {
42 url = compileURL(url, model, options);
43 }
44
45 // Compile the query string.
46 if (isPlainObject(query) && isFunction(encodeQueryString)) {
47 query = encodeQueryString(query, options);
48 array = url.split('#'); // There may be hash string in the url.
49 url = array[0];
50
51 if (url.indexOf('?') > -1) {
52 if (url.charAt(url.length - 1) === '&') {
53 url = url + query;
54 } else {
55 url = url + '&' + query;
56 }
57 } else {
58 url = url + '?' + query;
59 }
60
61 array[0] = url;
62 url = array.join('#');
63 }
64
65 return url;
66}
67
68module.exports = buildURL;