1

I have HttpService and i want to make some refreshTokenInterceptor, but actually i have a problem with adding then/catch chain from handle method which is implemented by my interceptors.

class HttpService {
constructor(private interceptors: Interceptor[]) {

}

get() {
    this.makeRequest()
}
post() {
    this.makeRequest();
}

//other http methods;

makeRequest(patch, body) {
    const request = { ...someData }

    return this.interceptors.map(interceptor => intercepor.handle(request))
        .then(modifiedReq => fetch(patch, modifiedBody))
        .then(res => res.json())

    }
}

ExampleInterceptor() {
    handle (req) {
        Promise.resolve(req)
            .then(req.headers.authentication = 'Auth Token')
            .catch(req => { refreshToken and retry request } )
    }
}

Do you have any idea how to make chain with then/catch blocks from handle methods ?

Actually i want to have something like angular interceptor with refresh token mechanism, cuz i didn't find better method to auto token refreshing at 401 status. Maybe you have better solution how to intercept these requests in your abstract layer like HttpService i made.

Piotrek332
  • 163
  • 2
  • 13
  • 2
    Don't you just need to `return` the promise from your `handle` method? – Liam Mar 07 '19 at 10:34
  • I try'ed but it doesn't work for me cuz its array of interceptors not a single one. – Piotrek332 Mar 07 '19 at 10:42
  • 2
    Yes, you also need to use `promise.all` or await each individual promise depending on how you expect this to work. [Like here](https://stackoverflow.com/a/37576787/542251) – Liam Mar 07 '19 at 11:19
  • It works as expected. Thank you :). But i still have some issues with my idea for refresh tokens. Mby someone implement similar thing with using some own HttpService. – Piotrek332 Mar 07 '19 at 13:01
  • Possible duplicate of [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Liam Mar 07 '19 at 13:03

0 Answers0