AxiosURLSearchParams.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. import toFormData from './toFormData.js';
  3. /**
  4. * It encodes a string by replacing all characters that are not in the unreserved set with
  5. * their percent-encoded equivalents
  6. *
  7. * @param {string} str - The string to encode.
  8. *
  9. * @returns {string} The encoded string.
  10. */
  11. function encode(str) {
  12. const charMap = {
  13. '!': '%21',
  14. "'": '%27',
  15. '(': '%28',
  16. ')': '%29',
  17. '~': '%7E',
  18. '%20': '+',
  19. };
  20. return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
  21. return charMap[match];
  22. });
  23. }
  24. /**
  25. * It takes a params object and converts it to a FormData object
  26. *
  27. * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
  28. * @param {Object<string, any>} options - The options object passed to the Axios constructor.
  29. *
  30. * @returns {void}
  31. */
  32. function AxiosURLSearchParams(params, options) {
  33. this._pairs = [];
  34. params && toFormData(params, this, options);
  35. }
  36. const prototype = AxiosURLSearchParams.prototype;
  37. prototype.append = function append(name, value) {
  38. this._pairs.push([name, value]);
  39. };
  40. prototype.toString = function toString(encoder) {
  41. const _encode = encoder
  42. ? function (value) {
  43. return encoder.call(this, value, encode);
  44. }
  45. : encode;
  46. return this._pairs
  47. .map(function each(pair) {
  48. return _encode(pair[0]) + '=' + _encode(pair[1]);
  49. }, '')
  50. .join('&');
  51. };
  52. export default AxiosURLSearchParams;