toFormData.js 7.7 KB

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