Last active
April 29, 2016 14:04
-
-
Save jacob414/a327d331171436ba70dce5a59610b059 to your computer and use it in GitHub Desktop.
A little convenience for many `fetch()` use cases
This file contains 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
"use strict"; | |
const qfApi = { | |
form: (src) => { | |
let form = new FormData() | |
for(let name in src) { | |
form.append(name, src[name]) | |
} | |
return form | |
}, | |
params: (src) => { | |
let params = new URLSearchParams() | |
for(let name in src) { | |
params.append(name, src[name]) | |
} | |
return params | |
}, | |
headers: (res) => { | |
let headObj = {} | |
for(let [name, val] of res.headers) { | |
headObj[name] = val | |
} | |
return headObj; | |
}, | |
readersFull: { | |
'application/json': 'json', | |
}, | |
readersStart: { | |
'text': 'text', | |
'image': 'blob', | |
}, | |
mimeReader: (res, mime) => { | |
const starting = mime.split('/')[0] | |
return (res[qfApi.readersFull[mime]] && res[qfApi.readersFull[mime]] || | |
res[qfApi.readersStart[starting]] && | |
res[qfApi.readersStart[starting]] || res.text) | |
}, | |
process: (res) => { | |
const mime = qfApi.headers(res)['content-type']; | |
if(res.ok && mime) { | |
return qfApi.mimeReader(res, mime).call(res); | |
} else if(res.ok) { | |
return res.text(); | |
} else { | |
throw new Error(`Fetch of ${url} failed with ${res.status}`); | |
} | |
}, | |
post: (url, json, form) => { | |
return fetch(url, {method: 'POST', credentials: 'same-origin', | |
body: form && qfApi.form(form) || JSON.stringify(json) | |
}).then(qfApi.process); | |
}, | |
get: (url, params) => ( | |
fetch(`${url}?${qfApi.params(params)}`, | |
{credentials:'same-origin'}).then(qfApi.process) | |
) | |
} | |
// Ad-hoc test cases | |
qfApi.post('http://httpbin.org/post', {foo: 'bar'}) | |
.then ((data) => { | |
console.log('JSON echo', data.json); | |
}) | |
.catch((failure) => { | |
console.log('FAIL', failure); | |
}); | |
qfApi.post('http://httpbin.org/post', false, {foo: 'bar'}) | |
.then ((data => { | |
console.log('FORM echo', data.form); | |
})) | |
qfApi.get('http://httpbin.org/get', {foo: 'bar'}) | |
.then ((data) => { | |
console.log('GET JSON Echo', data.args); | |
}); | |
qfApi.get('http://httpbin.org/html') | |
.then ((html) => { | |
console.log('HTML', html); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment