elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.83k stars 98 forks source link

[Feature request] Support (nested) objects in formData #68

Closed itsgoingd closed 4 years ago

itsgoingd commented 4 years ago

The formData method can already handle arrays as seen here:

https://github.com/elbywan/wretch/blob/master/src/wretcher.ts#L312-L324

But many server-side languages like PHP or Rails also support objects and even nested data, eg. { 'foo[bar]': 123, 'foo[baz][bar]': 456 }.

It would be very helpful if wretch supported this, should be an easy change to the convertFormData method above.

I'm down to work on a PR if you agree on this feature.

elbywan commented 4 years ago

Hi @itsgoingd,

It would be very helpful if wretch supported this

Indeed, thanks for the suggestion!

should be an easy change to the convertFormData method above.

Actually there are some hidden subtlties, so I took the liberty of implementing the feature (which is now done and published in v1.7.0).

Here is the updated documentation.

I kept the current behaviour as the default because a common use of FormData is to upload files (most likely Blob instances in the browser, and ReadableStream or Buffer instances when using a node.js polyfill) which are also of type "object" and should not be treated the same way.

I hope this change will suit your needs!

itsgoingd commented 4 years ago

Hey, thanks for including this!

Found a small issue - combination of null values and nesting, eg. formData({ foo: null}, true), leads to a crash where null is passed to Object.entries().

Looks like this check will need special handling of nulls, since typeof null is object 🤦‍♂

https://github.com/elbywan/wretch/blob/master/src/wretcher.ts#L329-L335

elbywan commented 4 years ago

Woops indeed! I just published a new release with the fix (v1.7.1).

Thanks, good catch 👍!

itsgoingd commented 4 years ago

Works great, thanks again.