Skip to content

Instantly share code, notes, and snippets.

@kaid
Created August 5, 2015 11:01
Show Gist options
  • Save kaid/15451043b5c09373913f to your computer and use it in GitHub Desktop.
Save kaid/15451043b5c09373913f to your computer and use it in GitHub Desktop.
Req.js simple fetch API wrapper with request and response processors.
export default class Req {
constructor({headers = {}, preProcessors = [], postProcessors = []} = {}) {
this.options = {};
this.options.headers = headers;
this.options.mode = "cors";
this.preProcessors = preProcessors;
this.postProcessors = postProcessors;
Object.freeze(this.options);
}
send({method, url, body} = {}) {
const options = {headers: this.headers};
if (body) options.body = body;
const request = this.preProcessors.reduce((request, preProcessor) => {
return preProcessor(request);
}, new Request(url, options));
return fetch(request).then((response) => {
return this.postProcessors.reduce((response, postProcessors) => {
return postProcessors(response);
}, response);
});
}
get(url) {
return this.send({method: "GET", url});
}
delete(url) {
return this.send({method: "DELETE", url});
}
post(url, body) {
return this.send({method: "POST", url, body});
}
put(url, body) {
return this.send({method: "PUT", url, body});
}
patch(url, body) {
return this.send({method: "PATCH", url, body});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment