toFormData.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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.concat(key).map(function each(token, i) {
  38. // eslint-disable-next-line no-param-reassign
  39. token = removeBrackets(token);
  40. return !dots && i ? '[' + token + ']' : token;
  41. }).join(dots ? '.' : '');
  42. }
  43. /**
  44. * If the array is an array and none of its elements are visitable, then it's a flat array.
  45. *
  46. * @param {Array<any>} arr - The array to check
  47. *
  48. * @returns {boolean}
  49. */
  50. function isFlatArray(arr) {
  51. return utils.isArray(arr) && !arr.some(isVisitable);
  52. }
  53. const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
  54. return /^is[A-Z]/.test(prop);
  55. });
  56. /**
  57. * Convert a data object to FormData
  58. *
  59. * @param {Object} obj
  60. * @param {?Object} [formData]
  61. * @param {?Object} [options]
  62. * @param {Function} [options.visitor]
  63. * @param {Boolean} [options.metaTokens = true]
  64. * @param {Boolean} [options.dots = false]
  65. * @param {?Boolean} [options.indexes = false]
  66. *
  67. * @returns {Object}
  68. **/
  69. /**
  70. * It converts an object into a FormData object
  71. *
  72. * @param {Object<any, any>} obj - The object to convert to form data.
  73. * @param {string} formData - The FormData object to append to.
  74. * @param {Object<string, any>} options
  75. *
  76. * @returns
  77. */
  78. function toFormData(obj, formData, options) {
  79. if (!utils.isObject(obj)) {
  80. throw new TypeError('target must be an object');
  81. }
  82. // eslint-disable-next-line no-param-reassign
  83. formData = formData || new (PlatformFormData || FormData)();
  84. // eslint-disable-next-line no-param-reassign
  85. options = utils.toFlatObject(options, {
  86. metaTokens: true,
  87. dots: false,
  88. indexes: false
  89. }, false, function defined(option, source) {
  90. // eslint-disable-next-line no-eq-null,eqeqeq
  91. return !utils.isUndefined(source[option]);
  92. });
  93. const metaTokens = options.metaTokens;
  94. // eslint-disable-next-line no-use-before-define
  95. const visitor = options.visitor || defaultVisitor;
  96. const dots = options.dots;
  97. const indexes = options.indexes;
  98. const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
  99. const useBlob = _Blob && utils.isSpecCompliantForm(formData);
  100. if (!utils.isFunction(visitor)) {
  101. throw new TypeError('visitor must be a function');
  102. }
  103. function convertValue(value) {
  104. if (value === null) return '';
  105. if (utils.isDate(value)) {
  106. return value.toISOString();
  107. }
  108. if (!useBlob && utils.isBlob(value)) {
  109. throw new AxiosError('Blob is not supported. Use a Buffer instead.');
  110. }
  111. if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
  112. return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
  113. }
  114. return value;
  115. }
  116. /**
  117. * Default visitor.
  118. *
  119. * @param {*} value
  120. * @param {String|Number} key
  121. * @param {Array<String|Number>} path
  122. * @this {FormData}
  123. *
  124. * @returns {boolean} return true to visit the each prop of the value recursively
  125. */
  126. function defaultVisitor(value, key, path) {
  127. let arr = value;
  128. if (value && !path && typeof value === 'object') {
  129. if (utils.endsWith(key, '{}')) {
  130. // eslint-disable-next-line no-param-reassign
  131. key = metaTokens ? key : key.slice(0, -2);
  132. // eslint-disable-next-line no-param-reassign
  133. value = JSON.stringify(value);
  134. } else if (
  135. (utils.isArray(value) && isFlatArray(value)) ||
  136. ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))
  137. )) {
  138. // eslint-disable-next-line no-param-reassign
  139. key = removeBrackets(key);
  140. arr.forEach(function each(el, index) {
  141. !(utils.isUndefined(el) || el === null) && formData.append(
  142. // eslint-disable-next-line no-nested-ternary
  143. indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
  144. convertValue(el)
  145. );
  146. });
  147. return false;
  148. }
  149. }
  150. if (isVisitable(value)) {
  151. return true;
  152. }
  153. formData.append(renderKey(path, key, dots), convertValue(value));
  154. return false;
  155. }
  156. const stack = [];
  157. const exposedHelpers = Object.assign(predicates, {
  158. defaultVisitor,
  159. convertValue,
  160. isVisitable
  161. });
  162. function build(value, path) {
  163. if (utils.isUndefined(value)) return;
  164. if (stack.indexOf(value) !== -1) {
  165. throw Error('Circular reference detected in ' + path.join('.'));
  166. }
  167. stack.push(value);
  168. utils.forEach(value, function each(el, key) {
  169. const result = !(utils.isUndefined(el) || el === null) && visitor.call(
  170. formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers
  171. );
  172. if (result === true) {
  173. build(el, path ? path.concat(key) : [key]);
  174. }
  175. });
  176. stack.pop();
  177. }
  178. if (!utils.isObject(obj)) {
  179. throw new TypeError('data must be an object');
  180. }
  181. build(obj);
  182. return formData;
  183. }
  184. export default toFormData;