-
Notifications
You must be signed in to change notification settings - Fork 3
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
Is there alternative for _isRetry
property?
#28
Labels
question
Further information is requested
Comments
Currently, no import xior, { XiorResponse, XiorError } from 'xior';
import errorRetry from 'xior/plugins/error-retry';
import setupTokenRefresh from 'xior/plugins/token-refresh';
const xiorWithAuth = xior.create();
xiorWithAuth.plugins.use(
errorRetry({
onRetry(config, error, count) {
(config as any)._isRetry = true;
(config as any)._retryCount = count;
},
})
); And also there are two plugins already support to refresh token and make it easier:
for example: import xior, { XiorResponse, XiorError } from 'xior';
import errorRetry from 'xior/plugins/error-retry';
import setupTokenRefresh from 'xior/plugins/token-refresh';
const xiorWithAuth = xior.create();
const TOKEN_KEY = 'TOKEN';
function getToken() {
return localStorage.getItem(TOKEN_KEY);
}
function setToken(token: string) {
return localStorage.setItem(TOKEN_KEY, token);
}
function deleteToken() {
return localStorage.getItem(TOKEN_KEY);
}
xiorWithAuth.interceptors.request.use((config) => {
const token = getToken();
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
});
function shouldRefresh(error: XiorError) {
const token = getToken();
if (!token) return false;
return error?.response?.status === 401;
}
xiorWithAuth.plugins.use(
errorRetry({
enableRetry: (config, error) => {
if (error?.response && shouldRefresh(error)) {
return true;
}
// return false // if don't want retry return false
},
})
);
setupTokenRefresh(xiorWithAuth, {
shouldRefresh,
async refreshToken(error) {
try {
const { data } = await authService.getNewTokens();
if (data.token) {
setToken(data.token);
} else {
throw error;
}
} catch (e) {
// something wrong, delete old token
deleteToken();
return Promise.reject(error);
}
},
}); |
suhaotian
added
enhancement
New feature or request
question
Further information is requested
and removed
enhancement
New feature or request
labels
Jul 25, 2024
looks awesome, thanks a lot! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: