Closed lucascerci closed 4 years ago
today we doing like this
const shouldRefreshToken = error => error.response.status === 401;
when the request return 401 we refresh token but its not cool let the system loose the permission to get again, i thinked in something like:
const shouldRefreshToken = when token.expire(date) is about to expire, call the refresh again. im doing this already with the code and timeouts but yet its not perfect
Oh, I see. Basically when you know the date & time when token will expire, then refresh it just before it expires, not when you get the first 401 response, right?
Hm, you cannot really do that with the current refresh-fetch
package, because shouldRefreshToken
is called only when there is an error from request, not before every request.
But it's actually a simpler setup, which can be implemented in just a few lines without the need of refresh-fetch
package I think. Something like:
import merge from "lodash/merge";
let token = null;
let tokenExpiresIn = null;
const refreshFetch = (url, options = {}) => {
let refreshTokenPromise = Promise.resolve();
if (shouldRefreshToken()) {
refreshTokenPromise = refreshToken();
}
let optionsWithToken = options;
if (token !== null) {
optionsWithToken = merge({}, options, {
headers: {
Authorization: `Bearer ${token}`,
},
});
}
return refreshTokenPromise.then(() => fetch(url, optionsWithToken));
};
const shouldRefreshToken = () => {
if (tokenExpiresIn === null) {
return true;
}
const now = new Date().getTime();
const willExpireInAMinute = tokenExpiresIn < now + 60000;
return willExpireInAMinute;
};
const refreshToken = () => {
// Do the refreshing and set token & tokenExpiresIn
};
By now im using your package as a second possibility to user stay logged in. Its working like this but i will soon when i get back to it try to do like your example with promises, ty, i will close it now
const refreshTokenWithExp = () => { if(retrieveToken() != null) { setTimeout(() => { refreshToken() }, calculateTimeToRefresh() - 10000); //10000 = 10 seconds before token expire } }
const saveToken = token => { Cookies.set(COOKIE_NAME, token, {domain: process.env.REACT_APP_BASE_COOKIE_URL}) setTimeout(() => { refreshToken() }, calculateTimeToRefresh()); };
Hi @lucascerci, not sure what you mean by "when expire with a expire date", could you elaborate a little bit more?