[d565449] | 1 | 'use strict';
|
---|
| 2 |
|
---|
| 3 | import utils from '../utils.js';
|
---|
| 4 | import AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';
|
---|
| 5 |
|
---|
| 6 | /**
|
---|
| 7 | * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
|
---|
| 8 | * URI encoded counterparts
|
---|
| 9 | *
|
---|
| 10 | * @param {string} val The value to be encoded.
|
---|
| 11 | *
|
---|
| 12 | * @returns {string} The encoded value.
|
---|
| 13 | */
|
---|
| 14 | function encode(val) {
|
---|
| 15 | return encodeURIComponent(val).
|
---|
| 16 | replace(/%3A/gi, ':').
|
---|
| 17 | replace(/%24/g, '$').
|
---|
| 18 | replace(/%2C/gi, ',').
|
---|
| 19 | replace(/%20/g, '+').
|
---|
| 20 | replace(/%5B/gi, '[').
|
---|
| 21 | replace(/%5D/gi, ']');
|
---|
| 22 | }
|
---|
| 23 |
|
---|
| 24 | /**
|
---|
| 25 | * Build a URL by appending params to the end
|
---|
| 26 | *
|
---|
| 27 | * @param {string} url The base of the url (e.g., http://www.google.com)
|
---|
| 28 | * @param {object} [params] The params to be appended
|
---|
[0c6b92a] | 29 | * @param {?(object|Function)} options
|
---|
[d565449] | 30 | *
|
---|
| 31 | * @returns {string} The formatted url
|
---|
| 32 | */
|
---|
| 33 | export default function buildURL(url, params, options) {
|
---|
| 34 | /*eslint no-param-reassign:0*/
|
---|
| 35 | if (!params) {
|
---|
| 36 | return url;
|
---|
| 37 | }
|
---|
| 38 |
|
---|
| 39 | const _encode = options && options.encode || encode;
|
---|
| 40 |
|
---|
[0c6b92a] | 41 | if (utils.isFunction(options)) {
|
---|
| 42 | options = {
|
---|
| 43 | serialize: options
|
---|
| 44 | };
|
---|
| 45 | }
|
---|
| 46 |
|
---|
[d565449] | 47 | const serializeFn = options && options.serialize;
|
---|
| 48 |
|
---|
| 49 | let serializedParams;
|
---|
| 50 |
|
---|
| 51 | if (serializeFn) {
|
---|
| 52 | serializedParams = serializeFn(params, options);
|
---|
| 53 | } else {
|
---|
| 54 | serializedParams = utils.isURLSearchParams(params) ?
|
---|
| 55 | params.toString() :
|
---|
| 56 | new AxiosURLSearchParams(params, options).toString(_encode);
|
---|
| 57 | }
|
---|
| 58 |
|
---|
| 59 | if (serializedParams) {
|
---|
| 60 | const hashmarkIndex = url.indexOf("#");
|
---|
| 61 |
|
---|
| 62 | if (hashmarkIndex !== -1) {
|
---|
| 63 | url = url.slice(0, hashmarkIndex);
|
---|
| 64 | }
|
---|
| 65 | url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
|
---|
| 66 | }
|
---|
| 67 |
|
---|
| 68 | return url;
|
---|
| 69 | }
|
---|