buildURL.js 1.6 KB

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