-
-
Save vvasilev-/178abe13f5428a3a7095998d4ecb0911 to your computer and use it in GitHub Desktop.
Axios interceptors for token refreshing and more than 2 async requests available
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let isRefreshing = false; | |
let refreshSubscribers = []; | |
const instance = axios.create({ | |
baseURL: Config.API_URL, | |
}); | |
instance.interceptors.response.use(response => { | |
return response; | |
}, error => { | |
const { config, response: { status } } = error; | |
const originalRequest = config; | |
if (status === 498) { | |
if (!isRefreshing) { | |
isRefreshing = true; | |
refreshAccessToken() | |
.then(newToken => { | |
isRefreshing = false; | |
onRrefreshed(newToken); | |
}); | |
} | |
const retryOrigReq = new Promise((resolve, reject) => { | |
subscribeTokenRefresh(token => { | |
// replace the expired token and retry | |
originalRequest.headers['Authorization'] = 'Bearer ' + token; | |
resolve(axios(originalRequest)); | |
}); | |
}); | |
return retryOrigReq; | |
} else { | |
return Promise.reject(error); | |
} | |
}); | |
subscribeTokenRefresh(cb) { | |
refreshSubscribers.push(cb); | |
} | |
onRrefreshed(token) { | |
refreshSubscribers.map(cb => cb(token)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment