elbywan / wretch

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

`.query()` should accept a string #20

Closed bendoh closed 6 years ago

bendoh commented 6 years ago

Some web applications use non-standard query strings that aren't necessarily an ampersand-separated list of keys and urlencoded values.

wretch should allow this case by accepting a string value in .query() and appending that to the URL after the ? verbatim.

elbywan commented 6 years ago

Hi @bendoh,

Thanks for the suggestion and the PR !

wretch should allow this case by accepting a string value in .query() and appending that to the URL after the ? verbatim.

Actually you can use .url() already to append an arbitrary string 😉

bendoh commented 6 years ago

Thanks for getting back. This change arose from a use case where both a query string was appended in the url explicitly, and additional arguments were passed in as an object to .query. The latter knocked out the former, which led to a bit of confusion. I hope this change makes the API a bit more clear, flexible and intuitive in that .query becomes the canonical way to set the query string, and appending it to the url parameter is discouraged.

The use case was to use jquery-param to encode the query string from nested composite values for consumption by PHP. Wretch doesn’t prepare nested objects in that way — and I wouldn’t think it is its responsibility to do so. This allows us to use whatever encoding scheme we want and still maintain the fluid interface, ie,

wretch(“/foo”).query(jParam(nestedObject))...

elbywan commented 6 years ago

@bendoh Good point 😄.

I integrated your commit in the dev branch, and also tweaked .query a bit so that now it can be chained like the other methods :

let w = wretch("http://example.com")
// url is http://example.com
w = w.query({ a: 1, b: 2 })
// url is now http://example.com?a=1&b=2
w = w.query({ c: 3, d: [4, 5] })
// url is now http://example.com?a=1&b=2c=3&d=4&d=5
w = w.query("five&six&seven=eight")
// url is now http://example.com?a=1&b=2c=3&d=4&d=5&five&six&seven=eight
w = w.query({ reset: true }, true)
// url is now  http://example.com?reset=true

If you are allright with this, I can publish a new package version asap.

elbywan commented 6 years ago

Fixed with the 1.2.0 release 📦