toFormData.js 7.6 KB

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. 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. const option = (name, fallback) => {
  92. const value = utils.getSafeProp(options, name);
  93. return utils.isUndefined(value) ? fallback : value;
  94. };
  95. const metaTokens = option('metaTokens', true);
  96. // eslint-disable-next-line no-use-before-define
  97. const visitor = option('visitor') || defaultVisitor;
  98. const dots = option('dots', false);
  99. const indexes = option('indexes', false);
  100. const _Blob = option('Blob') || (typeof Blob !== 'undefined' && Blob);
  101. const maxDepth = option('maxDepth', DEFAULT_FORM_DATA_MAX_DEPTH);
  102. const useBlob = _Blob && utils.isSpecCompliantForm(formData);
  103. const stack = [];
  104. if (!utils.isFunction(visitor)) {
  105. throw new TypeError('visitor must be a function');
  106. }
  107. function convertValue(value) {
  108. if (value === null) return '';
  109. if (utils.isDate(value)) {
  110. return value.toISOString();
  111. }
  112. if (utils.isBoolean(value)) {
  113. return value.toString();
  114. }
  115. if (!useBlob && utils.isBlob(value)) {
  116. throw new AxiosError('Blob is not supported. Use a Buffer instead.');
  117. }
  118. if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
  119. if (useBlob && typeof _Blob === 'function') {
  120. return new _Blob([value]);
  121. }
  122. if (PlatformBuffer && PlatformBuffer.isBufferAvailable()) {
  123. return PlatformBuffer.from(value);
  124. }
  125. throw new AxiosError(
  126. 'Blob is not supported. Use a Buffer instead.',
  127. AxiosError.ERR_NOT_SUPPORT
  128. );
  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;