buildURL.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. }
  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. /*eslint no-param-reassign:0*/
  30. if (!params) {
  31. return url;
  32. }
  33. const _encode = options && options.encode || encode;
  34. if (utils.isFunction(options)) {
  35. options = {
  36. serialize: options
  37. };
  38. }
  39. const serializeFn = options && options.serialize;
  40. let serializedParams;
  41. if (serializeFn) {
  42. serializedParams = serializeFn(params, options);
  43. } else {
  44. serializedParams = utils.isURLSearchParams(params) ?
  45. params.toString() :
  46. new AxiosURLSearchParams(params, options).toString(_encode);
  47. }
  48. if (serializedParams) {
  49. const hashmarkIndex = url.indexOf("#");
  50. if (hashmarkIndex !== -1) {
  51. url = url.slice(0, hashmarkIndex);
  52. }
  53. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  54. }
  55. return url;
  56. }