Skip to content

Instantly share code, notes, and snippets.

@little-dude
Created August 27, 2018 19:06
Show Gist options
  • Save little-dude/4f97e89c0f98113f74bc807f0d08a37f to your computer and use it in GitHub Desktop.
Save little-dude/4f97e89c0f98113f74bc807f0d08a37f to your computer and use it in GitHub Desktop.
custom fetcher
class ResponseError {
constructor(response) {
this.response = response;
}
async read() => {
return this.response
.text()
.then(body => {
return {
url: this.response.url,
code: this.response.status
text: this.response.statusText
body: body
};
});
}
}
class Request() {
constructor(request) {
this.request = request;
}
async send() {
fetch(this.request)
.then(response => {
if (response.ok) {
return response;
}
throw new ResponseError(response);
})
.then(response_ok => {
return response_ok.json();
})
.then(body => {
// FIXME: We assume the body contains valid JSON here
return JSON.stringify(body, null, 4);
})
.catch(e => {
if (e instanceof ResponseError) {
// FIXME: Is await ok here?
throw new RequestFailed(await response.read());
} else {
throw new RequestFailed(e.toString());
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment