toFormData.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 useBlob = _Blob && utils.isSpecCompliantForm(formData);
  108. if (!utils.isFunction(visitor)) {
  109. throw new TypeError('visitor must be a function');
  110. }
  111. function convertValue(value) {
  112. if (value === null) return '';
  113. if (utils.isDate(value)) {
  114. return value.toISOString();
  115. }
  116. if (utils.isBoolean(value)) {
  117. return value.toString();
  118. }
  119. if (!useBlob && utils.isBlob(value)) {
  120. throw new AxiosError('Blob is not supported. Use a Buffer instead.');
  121. }
  122. if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
  123. return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
  124. }
  125. return value;
  126. }
  127. /**
  128. * Default visitor.
  129. *
  130. * @param {*} value
  131. * @param {String|Number} key
  132. * @param {Array<String|Number>} path
  133. * @this {FormData}
  134. *
  135. * @returns {boolean} return true to visit the each prop of the value recursively
  136. */
  137. function defaultVisitor(value, key, path) {
  138. let arr = value;
  139. if (utils.isReactNative(formData) && utils.isReactNativeBlob(value)) {
  140. formData.append(renderKey(path, key, dots), convertValue(value));
  141. return false;
  142. }
  143. if (value && !path && typeof value === 'object') {
  144. if (utils.endsWith(key, '{}')) {
  145. // eslint-disable-next-line no-param-reassign
  146. key = metaTokens ? key : key.slice(0, -2);
  147. // eslint-disable-next-line no-param-reassign
  148. value = JSON.stringify(value);
  149. } else if (
  150. (utils.isArray(value) && isFlatArray(value)) ||
  151. ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)))
  152. ) {
  153. // eslint-disable-next-line no-param-reassign
  154. key = removeBrackets(key);
  155. arr.forEach(function each(el, index) {
  156. !(utils.isUndefined(el) || el === null) &&
  157. formData.append(
  158. // eslint-disable-next-line no-nested-ternary
  159. indexes === true
  160. ? renderKey([key], index, dots)
  161. : indexes === null
  162. ? key
  163. : key + '[]',
  164. convertValue(el)
  165. );
  166. });
  167. return false;
  168. }
  169. }
  170. if (isVisitable(value)) {
  171. return true;
  172. }
  173. formData.append(renderKey(path, key, dots), convertValue(value));
  174. return false;
  175. }
  176. const stack = [];
  177. const exposedHelpers = Object.assign(predicates, {
  178. defaultVisitor,
  179. convertValue,
  180. isVisitable,
  181. });
  182. function build(value, path) {
  183. if (utils.isUndefined(value)) return;
  184. if (stack.indexOf(value) !== -1) {
  185. throw Error('Circular reference detected in ' + path.join('.'));
  186. }
  187. stack.push(value);
  188. utils.forEach(value, function each(el, key) {
  189. const result =
  190. !(utils.isUndefined(el) || el === null) &&
  191. visitor.call(formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers);
  192. if (result === true) {
  193. build(el, path ? path.concat(key) : [key]);
  194. }
  195. });
  196. stack.pop();
  197. }
  198. if (!utils.isObject(obj)) {
  199. throw new TypeError('data must be an object');
  200. }
  201. build(obj);
  202. return formData;
  203. }
  204. export default toFormData;