Last active
October 15, 2021 19:12
-
-
Save mxmason/fd07f403c4b34a30dac933066b69725e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* 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); | |
} |
This file contains hidden or 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
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