-
-
Notifications
You must be signed in to change notification settings - Fork 615
Closed
Labels
enhancementNew feature or requestNew feature or requestopenapi-fetchRelevant to the openapi-fetch libraryRelevant to the openapi-fetch library
Description
Hello there! I've been trying to implement the refresh session functionality for quite some time using the response middleware.
The stumbling block is to retry the failed request inside the middleware. In the following code snippet, I am registering the Middleware and in the onResponse handler I'd like to add the retry line of the original request (look for the comment '// retry request here').
Any consultation would be greatly appreciated.
import { authService, TLoginResponse } from '@/shared/auth'
import { Middleware } from 'openapi-fetch'
let refreshPromise: Promise<TLoginResponse | undefined> | null = null
export const middleware: Middleware = {
async onResponse({ response, request }) {
if (response.ok) return response
else {
if (response.status === 401) {
try {
if (!refreshPromise) {
refreshPromise = authService.refreshSession()
}
const refreshResponse = await refreshPromise
if (refreshResponse) {
authService.setAccessToken(refreshResponse)
authService.setRefreshToken(refreshResponse)
request.headers.set('Authorization', `Bearer ${refreshResponse.accessToken}`)
try {
return // retry request here
} catch (innerError) {
if (innerError.status === 401) {
throw innerError
}
}
}
} catch (error) {
authService.setRefreshToken({ refreshToken: null })
authService.setAccessToken({ accessToken: null })
} finally {
refreshPromise = null
}
}
}
},
}Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or requestopenapi-fetchRelevant to the openapi-fetch libraryRelevant to the openapi-fetch library