Created
August 27, 2018 19:06
-
-
Save little-dude/4f97e89c0f98113f74bc807f0d08a37f to your computer and use it in GitHub Desktop.
custom fetcher
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
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