UNPKG

wretch

Version:

A tiny wrapper built around fetch with an intuitive syntax.

41 lines 1.42 kB
function convertFormData(formObject, recursive = false, formData = new FormData(), ancestors = []) { Object.entries(formObject).forEach(([key, value]) => { let formKey = ancestors.reduce((acc, ancestor) => (acc ? `${acc}[${ancestor}]` : ancestor), null); formKey = formKey ? `${formKey}[${key}]` : key; if (value instanceof Array || (globalThis.FileList && value instanceof FileList)) { for (const item of value) formData.append(formKey, item); } else if (recursive && typeof value === "object" && (!(recursive instanceof Array) || !recursive.includes(key))) { if (value !== null) { convertFormData(value, recursive, formData, [...ancestors, key]); } } else { formData.append(formKey, value); } }); return formData; } /** * Adds the ability to convert a an object to a FormData and use it as a request body. * * ```js * import FormDataAddon from "wretch/addons/formData" * * wretch().addon(FormDataAddon) * ``` */ const formData = { wretch: { formData(formObject, options = {}) { var _a; return this.body(convertFormData(formObject, (_a = options.recursive) !== null && _a !== void 0 ? _a : false)); } } }; export default formData; //# sourceMappingURL=formData.js.map