- From: Eric Martin <notifications@github.com>
- Date: Tue, 20 Jun 2017 02:51:10 -0700
- To: whatwg/fetch <fetch@noreply.github.com>
- Cc: Subscribed <subscribed@noreply.github.com>
- Message-ID: <whatwg/fetch/issues/196/309703601@github.com>
Here's a way that you can work around. Basically, you just build off an object containing `response` and `body` to next callbacks. This way you just read the Stream once, and you keep both variables in your scope. I do not know much about performance costs of this implementation, but so far, it never failed me 👍
```
class Api {
constructor() {
this.domain = 'http://localhost:5000';
}
fetch({url, body, headers = {}, onResponse = () => {}, onSuccess = () => {},
onError = () => {}, authenticated = false}) {
if(authenticated === true){
headers["Authorization"] =
"some authorization token here";
}
return fetch(this.domain.concat(url), { body: body, headers: headers })
.then((response) => {
return response.json().then((body) => {
return { response, body };
})
.then((request) => {
this.checkAuthentication(request, authenticated);
})
.then((request) => {
this.handleCallbacks(request, onResponse, onSuccess, onError);
});
});
}
checkAuthentication(request, authenticated){
if(authenticated === true && request.response.status === 401){
// STUB
}
}
handleCallbacks(request, onResponse, onSuccess, onError){
console.log(onResponse);
onResponse(request.response, request.body);
(request.response.status < 200 || request.response.status >= 300) ?
onError(request.response, body):
onSuccess(request.response, body);
}
}
export default Api;
```
As you can see you can access both `response` and `body` from completely external methods. Anonymous functions to pass parameters out to external methods may seem a bit overkill at first, but haven't found a better solution atm.
Hope this helps :)
--
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/196#issuecomment-309703601
Received on Tuesday, 20 June 2017 09:51:46 UTC