Skip to content

Instantly share code, notes, and snippets.

@mxmason
Last active October 15, 2021 19:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxmason/fd07f403c4b34a30dac933066b69725e to your computer and use it in GitHub Desktop.
Save mxmason/fd07f403c4b34a30dac933066b69725e to your computer and use it in GitHub Desktop.
/**
* A small lib for fetching with query parameters.
* CREDIT: discussion in this issue thread: https://github.com/github/fetch/issues/256
* @param {String} url
* @param {Object} [opts={}] The init options for the fetch request
* @param {Object} [opts.params] The key-value pairs that will be used to build a query string
* @example
* // Makes a GET request to `foo.com`
* soFetch('https://foo.com');
* // Makes a GET request to foo.com with query params
* soFetch('https://foo.com', {query: {bar: 'baz'});
*/
function soFetch(url, opts = {}) {
const hasOwn = Object.prototype.hasOwnProperty;
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
function encodeQueryParams(params) {
const esc = encodeURIComponent
const str = []
for (let k in params) {
if (hasProp(params, k)) {
str.push(esc(k) + '=' + esc(params[k]))
}
}
return str.join('&')
}
if (opts.query) {
url +=
(url.indexOf('?') === -1 ? '?' : '&') + encodeQueryParams(opts.query);
delete opts.query;
}
return fetch(url, opts);
}
function soFetch(e,n={}){const t=Object.prototype.hasOwnProperty;return n.query&&(e+=(-1===e.indexOf("?")?"?":"&")+function(e){const n=encodeURIComponent,o=[];for(let u in e)r=e,c=u,t.call(r,c)&&o.push(n(u)+"="+n(e[u]));var r,c;return o.join("&")}(n.query),delete n.query),fetch(e,n)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment