Last active
May 13, 2022 02:57
-
-
Save sidouglas/165224dfdce6b8b0e7738e83b73fe755 to your computer and use it in GitHub Desktop.
ObjectToForm Data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {Object} object | |
* @param {'GET'|'POST'|'PUT'|'PATCH'|'DELETE'} verb | |
* @returns {FormData} | |
*/ | |
export function objectToFormData (object, verb = 'POST') { | |
const formData = Object.keys(object).reduce((formData, key) => { | |
const value = typeof object[key] === 'boolean' | |
? Number(object[key]) | |
: object[key] | |
formData.append(key, value) | |
return formData | |
}, new FormData()) | |
// @see https://laravel.com/docs/9.x/routing#form-method-spoofing | |
if (verb === 'PUT' || verb === 'PATCH' || verb === 'DELETE') { | |
formData.append('_method', verb) | |
} | |
return formData | |
} | |
/* Test */ | |
it('converts an object to FormData', async () => { | |
const suite = { | |
'a=1&b=2&c=3': { | |
test: { | |
object: { | |
a: true, | |
b: '2', | |
c: 3 | |
}, | |
verb: 'POST', | |
}, | |
}, | |
'a=1&b=1&c=3&d=0&e=0&_method=PUT': { | |
test: { | |
object: { | |
a: true, | |
b: 1, | |
c: 3, | |
d: 0, | |
e: false | |
}, | |
verb: 'PUT', | |
}, | |
} | |
} | |
Object.entries(suite).forEach(([toEqual, testInput]) => { | |
const output = objectToFormData(testInput.test.object, testInput.test.verb) | |
expect(new URLSearchParams(output).toString()).toEqual(toEqual) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment