formDataToJSON.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. 'use strict';
  2. import utils from '../utils.js';
  3. import AxiosError from '../core/AxiosError.js';
  4. import { DEFAULT_FORM_DATA_MAX_DEPTH } from './toFormData.js';
  5. const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;
  6. function throwIfDepthExceeded(index) {
  7. if (index > MAX_DEPTH) {
  8. throw new AxiosError(
  9. 'FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH,
  10. AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED
  11. );
  12. }
  13. }
  14. /**
  15. * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
  16. *
  17. * @param {string} name - The name of the property to get.
  18. *
  19. * @returns An array of strings.
  20. */
  21. function parsePropPath(name) {
  22. // foo[x][y][z] -> ['foo', 'x', 'y', 'z']
  23. // foo.x.y.z -> ['foo', 'x', 'y', 'z']
  24. // A path is split on `.` and on `[...]` groups. A segment — whether written
  25. // in dot notation or captured inside brackets — may contain any character
  26. // except `.`, `[` and `]`, so a key like `user-name` or `user name` is kept
  27. // literal instead of being split (#5402). `.`, `[` and `]` keep their existing
  28. // meaning, e.g. `foo[bar.baz]` -> ['foo', 'bar', 'baz'] and `[]` is an array push.
  29. // Excluding `[` from the bracket group also makes the match fail fast at the
  30. // next `[`, so a malformed name cannot rescan to the end of the string from
  31. // every unmatched `[` — parsing stays linear in the length of the name.
  32. const path = [];
  33. const pattern = /[^.[\]]+|\[([^.[\]]*)]/g;
  34. let match;
  35. while ((match = pattern.exec(name)) !== null) {
  36. throwIfDepthExceeded(path.length);
  37. path.push(match[0] === '[]' ? '' : match[1] || match[0]);
  38. }
  39. return path;
  40. }
  41. /**
  42. * Convert an array to an object.
  43. *
  44. * @param {Array<any>} arr - The array to convert to an object.
  45. *
  46. * @returns An object with the same keys and values as the array.
  47. */
  48. function arrayToObject(arr) {
  49. const obj = {};
  50. const keys = Object.keys(arr);
  51. let i;
  52. const len = keys.length;
  53. let key;
  54. for (i = 0; i < len; i++) {
  55. key = keys[i];
  56. obj[key] = arr[key];
  57. }
  58. return obj;
  59. }
  60. function normalizeArray(value) {
  61. if (!utils.isArray(value)) return value;
  62. const keys = Object.keys(value);
  63. return keys.length !== value.length || keys.some((key, index) => key !== String(index))
  64. ? arrayToObject(value)
  65. : value;
  66. }
  67. function normalizeArrays(obj) {
  68. const pending = [obj];
  69. while (pending.length) {
  70. const target = pending.pop();
  71. Object.keys(target).forEach((key) => {
  72. const value = (target[key] = normalizeArray(target[key]));
  73. if (utils.isArray(value) || utils.isPlainObject(value)) {
  74. pending.push(value);
  75. }
  76. });
  77. }
  78. return obj;
  79. }
  80. /**
  81. * It takes a FormData object and returns a JavaScript object
  82. *
  83. * @param {string} formData The FormData object to convert to JSON.
  84. *
  85. * @returns {Object<string, any> | null} The converted object.
  86. */
  87. function formDataToJSON(formData) {
  88. function buildPath(path, value, target, index) {
  89. throwIfDepthExceeded(index);
  90. let name = path[index++];
  91. if (name === '__proto__') return true;
  92. const isNumericKey = Number.isFinite(+name);
  93. const isLast = index >= path.length;
  94. name = !name && utils.isArray(target) ? target.length : name;
  95. if (isLast) {
  96. if (utils.hasOwnProp(target, name)) {
  97. target[name] = normalizeArray(target[name]);
  98. target[name] = utils.isArray(target[name])
  99. ? target[name].concat(value)
  100. : [target[name], value];
  101. } else {
  102. target[name] = value;
  103. }
  104. return !isNumericKey;
  105. }
  106. if (!utils.hasOwnProp(target, name) || !utils.isObject(target[name])) {
  107. target[name] = [];
  108. }
  109. const result = buildPath(path, value, target[name], index);
  110. if (result && utils.isArray(target[name])) {
  111. target[name] = arrayToObject(target[name]);
  112. }
  113. return !isNumericKey;
  114. }
  115. if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
  116. const obj = {};
  117. utils.forEachEntry(formData, (name, value) => {
  118. buildPath(parsePropPath(name), value, obj, 0);
  119. });
  120. return normalizeArrays(obj);
  121. }
  122. return null;
  123. }
  124. export default formDataToJSON;