[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
|
---|
| 29 | * @param {?object} options
|
---|
| 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 |
|
---|
| 41 | const serializeFn = options && options.serialize;
|
---|
| 42 |
|
---|
| 43 | let serializedParams;
|
---|
| 44 |
|
---|
| 45 | if (serializeFn) {
|
---|
| 46 | serializedParams = serializeFn(params, options);
|
---|
| 47 | } else {
|
---|
| 48 | serializedParams = utils.isURLSearchParams(params) ?
|
---|
| 49 | params.toString() :
|
---|
| 50 | new AxiosURLSearchParams(params, options).toString(_encode);
|
---|
| 51 | }
|
---|
| 52 |
|
---|
| 53 | if (serializedParams) {
|
---|
| 54 | const hashmarkIndex = url.indexOf("#");
|
---|
| 55 |
|
---|
| 56 | if (hashmarkIndex !== -1) {
|
---|
| 57 | url = url.slice(0, hashmarkIndex);
|
---|
| 58 | }
|
---|
| 59 | url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
|
---|
| 60 | }
|
---|
| 61 |
|
---|
| 62 | return url;
|
---|
| 63 | }
|
---|