Created
August 5, 2015 11:01
-
-
Save kaid/15451043b5c09373913f to your computer and use it in GitHub Desktop.
Req.js simple fetch API wrapper with request and response processors.
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
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