Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle request retry or re-routing in middleware.afterFilters #100

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

bilouw
Copy link
Collaborator

@bilouw bilouw commented Sep 9, 2021

Hi guys,

Problem: I recently wanted to handle refresh token. My goal was to catch 401 response, get a new token, then retry the request that failed. However, there is no way to modify the response in the middleware.afterFilters function (to return the successfully response instead of the failed one).

Solution: I added a variable to MiddlewareStack Class named "newResponse: Response | null". If this variable is set in middleware.afterFilters function, it will be used as the new response instead of the original response passed to the middleware. I also added the requestOptions, so we can have all the information about the request that failed, to retry it for example. This way, we can handle retry request or re-routing in middleware.afterFilters.

Example - Catch 401 error, get new token then retry the request that failed:

middleware.afterFilters.push(async(response: Response, json: JSON, requestOptions: RequestInit) => {
  if (response.status === 401) {
    await UserModule.RefreshToken()

    requestOptions.headers.Authorization = `Bearer ${getToken()}`
    const result = await fetch(response.url, requestOptions)

    middleware.newResponse = result
  }
}

Don't hesitate to tell me if you think about better variable naming or better code implementation.

@bilouw bilouw changed the title feat: handle response retry or re-routing in middleware.afterFilters Handle response retry or re-routing in middleware.afterFilters Sep 9, 2021
@bilouw bilouw changed the title Handle response retry or re-routing in middleware.afterFilters Handle request retry or re-routing in middleware.afterFilters Sep 9, 2021
@superslau
Copy link

I have a similar use case. What are your thoughts on this PR @richmolj?

@bilouw
Copy link
Collaborator Author

bilouw commented Mar 7, 2022

Hi ! I use this feat on my fork since many month now, it seems to work pretty good.
If @richmolj or @wadetandy can accept this pull request, i will appreciate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants