AxiosURLSearchParams.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. '%00': '\x00'
  20. };
  21. return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
  22. return charMap[match];
  23. });
  24. }
  25. /**
  26. * It takes a params object and converts it to a FormData object
  27. *
  28. * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
  29. * @param {Object<string, any>} options - The options object passed to the Axios constructor.
  30. *
  31. * @returns {void}
  32. */
  33. function AxiosURLSearchParams(params, options) {
  34. this._pairs = [];
  35. params && toFormData(params, this, options);
  36. }
  37. const prototype = AxiosURLSearchParams.prototype;
  38. prototype.append = function append(name, value) {
  39. this._pairs.push([name, value]);
  40. };
  41. prototype.toString = function toString(encoder) {
  42. const _encode = encoder ? function(value) {
  43. return encoder.call(this, value, encode);
  44. } : encode;
  45. return this._pairs.map(function each(pair) {
  46. return _encode(pair[0]) + '=' + _encode(pair[1]);
  47. }, '').join('&');
  48. };
  49. export default AxiosURLSearchParams;