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