buildURL.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. import utils from '../utils.js';
  3. import AxiosURLSearchParams from './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. export 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. url = url || '';
  33. const _options = utils.isFunction(options)
  34. ? {
  35. serialize: options,
  36. }
  37. : options;
  38. // Read serializer options pollution-safely: own properties and methods on a
  39. // class/template prototype are honored, but values injected onto a polluted
  40. // Object.prototype are ignored.
  41. const _encode = utils.getSafeProp(_options, 'encode') || encode;
  42. const serializeFn = utils.getSafeProp(_options, 'serialize');
  43. let serializedParams;
  44. if (serializeFn) {
  45. serializedParams = serializeFn(params, _options);
  46. } else {
  47. serializedParams = utils.isURLSearchParams(params)
  48. ? params.toString()
  49. : new AxiosURLSearchParams(params, _options).toString(_encode);
  50. }
  51. if (serializedParams) {
  52. const hashmarkIndex = url.indexOf('#');
  53. if (hashmarkIndex !== -1) {
  54. url = url.slice(0, hashmarkIndex);
  55. }
  56. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  57. }
  58. return url;
  59. }