智慧水务管理系统 - 精河县供水工程综合管理平台

toFormData.js 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. 'use strict';
  2. import utils from '../utils.js';
  3. import AxiosError from '../core/AxiosError.js';
  4. // temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored
  5. import PlatformFormData from '../platform/node/classes/FormData.js';
  6. // Default nesting limit shared with the inverse transform (formDataToJSON) so
  7. // the FormData <-> JSON round-trip stays symmetric.
  8. export const DEFAULT_FORM_DATA_MAX_DEPTH = 100;
  9. /**
  10. * Determines if the given thing is a array or js object.
  11. *
  12. * @param {string} thing - The object or array to be visited.
  13. *
  14. * @returns {boolean}
  15. */
  16. function isVisitable(thing) {
  17. return utils.isPlainObject(thing) || utils.isArray(thing);
  18. }
  19. /**
  20. * It removes the brackets from the end of a string
  21. *
  22. * @param {string} key - The key of the parameter.
  23. *
  24. * @returns {string} the key without the brackets.
  25. */
  26. function removeBrackets(key) {
  27. return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;
  28. }
  29. /**
  30. * It takes a path, a key, and a boolean, and returns a string
  31. *
  32. * @param {string} path - The path to the current key.
  33. * @param {string} key - The key of the current object being iterated over.
  34. * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
  35. *
  36. * @returns {string} The path to the current key.
  37. */
  38. function renderKey(path, key, dots) {
  39. if (!path) return key;
  40. return path
  41. .concat(key)
  42. .map(function each(token, i) {
  43. // eslint-disable-next-line no-param-reassign
  44. token = removeBrackets(token);
  45. return !dots && i ? '[' + token + ']' : token;
  46. })
  47. .join(dots ? '.' : '');
  48. }
  49. /**
  50. * If the array is an array and none of its elements are visitable, then it's a flat array.
  51. *
  52. * @param {Array<any>} arr - The array to check
  53. *
  54. * @returns {boolean}
  55. */
  56. function isFlatArray(arr) {
  57. return utils.isArray(arr) && !arr.some(isVisitable);
  58. }
  59. const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
  60. return /^is[A-Z]/.test(prop);
  61. });
  62. /**
  63. * Convert a data object to FormData
  64. *
  65. * @param {Object} obj
  66. * @param {?Object} [formData]
  67. * @param {?Object} [options]
  68. * @param {Function} [options.visitor]
  69. * @param {Boolean} [options.metaTokens = true]
  70. * @param {Boolean} [options.dots = false]
  71. * @param {?Boolean} [options.indexes = false]
  72. *
  73. * @returns {Object}
  74. **/
  75. /**
  76. * It converts an object into a FormData object
  77. *
  78. * @param {Object<any, any>} obj - The object to convert to form data.
  79. * @param {string} formData - The FormData object to append to.
  80. * @param {Object<string, any>} options
  81. *
  82. * @returns
  83. */
  84. function toFormData(obj, formData, options) {
  85. if (!utils.isObject(obj)) {
  86. throw new TypeError('target must be an object');
  87. }
  88. // eslint-disable-next-line no-param-reassign
  89. formData = formData || new (PlatformFormData || FormData)();
  90. // eslint-disable-next-line no-param-reassign
  91. options = utils.toFlatObject(
  92. options,
  93. {
  94. metaTokens: true,
  95. dots: false,
  96. indexes: false,
  97. },
  98. false,
  99. function defined(option, source) {
  100. // eslint-disable-next-line no-eq-null,eqeqeq
  101. return !utils.isUndefined(source[option]);
  102. }
  103. );
  104. const metaTokens = options.metaTokens;
  105. // eslint-disable-next-line no-use-before-define
  106. const visitor = options.visitor || defaultVisitor;
  107. const dots = options.dots;
  108. const indexes = options.indexes;
  109. const _Blob = options.Blob || (typeof Blob !== 'undefined' && Blob);
  110. const maxDepth = options.maxDepth === undefined ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth;
  111. const useBlob = _Blob && utils.isSpecCompliantForm(formData);
  112. const stack = [];
  113. if (!utils.isFunction(visitor)) {
  114. throw new TypeError('visitor must be a function');
  115. }
  116. function convertValue(value) {
  117. if (value === null) return '';
  118. if (utils.isDate(value)) {
  119. return value.toISOString();
  120. }
  121. if (utils.isBoolean(value)) {
  122. return value.toString();
  123. }
  124. if (!useBlob && utils.isBlob(value)) {
  125. throw new AxiosError('Blob is not supported. Use a Buffer instead.');
  126. }
  127. if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
  128. return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
  129. }
  130. return value;
  131. }
  132. function throwIfMaxDepthExceeded(depth) {
  133. if (depth > maxDepth) {
  134. throw new AxiosError(
  135. 'Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth,
  136. AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED
  137. );
  138. }
  139. }
  140. function stringifyWithDepthLimit(value, depth) {
  141. if (maxDepth === Infinity) {
  142. return JSON.stringify(value);
  143. }
  144. const ancestors = [];
  145. return JSON.stringify(value, function limitDepth(_key, currentValue) {
  146. if (!utils.isObject(currentValue)) {
  147. return currentValue;
  148. }
  149. while (ancestors.length && ancestors[ancestors.length - 1] !== this) {
  150. ancestors.pop();
  151. }
  152. ancestors.push(currentValue);
  153. throwIfMaxDepthExceeded(depth + ancestors.length - 1);
  154. return currentValue;
  155. });
  156. }
  157. /**
  158. * Default visitor.
  159. *
  160. * @param {*} value
  161. * @param {String|Number} key
  162. * @param {Array<String|Number>} path
  163. * @this {FormData}
  164. *
  165. * @returns {boolean} return true to visit the each prop of the value recursively
  166. */
  167. function defaultVisitor(value, key, path) {
  168. let arr = value;
  169. if (utils.isReactNative(formData) && utils.isReactNativeBlob(value)) {
  170. formData.append(renderKey(path, key, dots), convertValue(value));
  171. return false;
  172. }
  173. if (value && !path && typeof value === 'object') {
  174. if (utils.endsWith(key, '{}')) {
  175. // eslint-disable-next-line no-param-reassign
  176. key = metaTokens ? key : key.slice(0, -2);
  177. // eslint-disable-next-line no-param-reassign
  178. value = stringifyWithDepthLimit(value, 1);
  179. } else if (
  180. (utils.isArray(value) && isFlatArray(value)) ||
  181. ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)))
  182. ) {
  183. // eslint-disable-next-line no-param-reassign
  184. key = removeBrackets(key);
  185. arr.forEach(function each(el, index) {
  186. !(utils.isUndefined(el) || el === null) &&
  187. formData.append(
  188. // eslint-disable-next-line no-nested-ternary
  189. indexes === true
  190. ? renderKey([key], index, dots)
  191. : indexes === null
  192. ? key
  193. : key + '[]',
  194. convertValue(el)
  195. );
  196. });
  197. return false;
  198. }
  199. }
  200. if (isVisitable(value)) {
  201. return true;
  202. }
  203. formData.append(renderKey(path, key, dots), convertValue(value));
  204. return false;
  205. }
  206. const exposedHelpers = Object.assign(predicates, {
  207. defaultVisitor,
  208. convertValue,
  209. isVisitable,
  210. });
  211. function build(value, path, depth = 0) {
  212. if (utils.isUndefined(value)) return;
  213. throwIfMaxDepthExceeded(depth);
  214. if (stack.indexOf(value) !== -1) {
  215. throw new Error('Circular reference detected in ' + path.join('.'));
  216. }
  217. stack.push(value);
  218. utils.forEach(value, function each(el, key) {
  219. const result =
  220. !(utils.isUndefined(el) || el === null) &&
  221. visitor.call(formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers);
  222. if (result === true) {
  223. build(el, path ? path.concat(key) : [key], depth + 1);
  224. }
  225. });
  226. stack.pop();
  227. }
  228. if (!utils.isObject(obj)) {
  229. throw new TypeError('data must be an object');
  230. }
  231. build(obj);
  232. return formData;
  233. }
  234. export default toFormData;