Query string hook
See original GitHub issueI love this library and its commitment to simplicity. I always reach for it on new projects. One thing I always need to add in is query string support. I’m glad this lib doesn’t include this out of the box, because there are so many ways to stringify query string objects.
Myself, and many devs I work with, aren’t satisfied with a system where the query string is built and then appended to the URI before passing it into xhr. In other words, this API:
const query = qs.stringify({ ... });
xhr.get(`/things?${query}`)
A declarative approach would be more preferable. However, it’s not trivial to wrap xhr
to add in support for a qs
option due to the numerous argument signatures it accepts. It’s not impossible, by any means, but this is what I currently do:
export default function request(uri, options, cb) {
let params = {};
// This handles the `xhr(options, cb)` syntax
if (typeof uri === 'object') {
params = uri;
}
// This handles the `xhr(uri, options, cb)` syntax
else if (typeof uri === 'string' && typeof options === 'object') {
params = options;
params.uri = uri;
}
// This handles the `xhr(uri, cb)` syntax
else {
params.uri = uri;
}
// This adds support for the `qs` option
const urlString = params.uri ? params.uri : params.url;
params.uri = buildUrl(urlString, params);
let callback;
if (typeof options === 'function') {
callback = options;
} else if (typeof cb === 'function') {
callback = cb;
}
return xhr(params, callback);
}
A simpler alternative would be a hook within this library that would work like follows:
- If the hook is present, the value of the
qs
option will be passed to it. The return value of the hook is appended to the URI. - If the hook is not present, nothing happens
- By default, there is no hook
The example code I wrote at the start of this issue would then become:
import xhr from 'xhr';
import qs from 'your-favorite-qs-lib';
xhr.queryStringStringify = qs.stringify;
xhr.get('/things', {qs: { ... });`
I’d be happy to whip up a PR if there’s interest. Otherwise, I understand the desire to keep this lib slim. No worries, either way!
Thanks for reading!
Issue Analytics
- State:
- Created 6 years ago
- Comments:7 (3 by maintainers)
Top GitHub Comments
@jmeas Sure, just to see what the API could be, we can then iterate and see if we come up with something that’s not going to confuse anyone.
Resolved in #160 to be released in v3. Closing.