graphiti-api / spraypaint.js

Graphiti Client / Javascript ORM / JSONAPI
MIT License
108 stars 69 forks source link

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

Open bilouw opened 3 years ago

bilouw commented 3 years ago

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.

superslau commented 2 years ago

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

bilouw commented 2 years ago

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.