buildURL.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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} 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. const serializeFn = options && options.serialize;
  37. let serializedParams;
  38. if (serializeFn) {
  39. serializedParams = serializeFn(params, options);
  40. } else {
  41. serializedParams = utils.isURLSearchParams(params) ?
  42. params.toString() :
  43. new AxiosURLSearchParams(params, options).toString(_encode);
  44. }
  45. if (serializedParams) {
  46. const hashmarkIndex = url.indexOf("#");
  47. if (hashmarkIndex !== -1) {
  48. url = url.slice(0, hashmarkIndex);
  49. }
  50. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  51. }
  52. return url;
  53. }