toFormData.js 6.6 KB

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