buildURL.js 1.6 KB

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