Last active
November 15, 2022 00:47
-
-
Save jezielm7/7a785d715aa338641f17e12b458fc4dc to your computer and use it in GitHub Desktop.
File sample to apply refresh token
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
import axios, { AxiosError } from 'axios'; | |
import AsyncStorage from '@react-native-async-storage/async-storage'; | |
const api = axios.create({ | |
baseURL: 'http://localhost:3000', | |
}); | |
api.interceptors.request.use( | |
async function (config) { | |
if (config.url !== '/auth') { | |
const token = await AsyncStorage.getItem('@auth/token'); | |
if (token) { | |
config.headers = { | |
...config.headers, | |
Authorization: `Bearer ${token}`, | |
}; | |
} | |
} | |
return config; | |
}, | |
function (error) { | |
return Promise.reject(error); | |
}, | |
); | |
api.interceptors.response.use( | |
async function (response) { | |
return response; | |
}, | |
async function (error: AxiosError) { | |
const local_access_token = await AsyncStorage.getItem('@auth/token'); | |
if (error.response) { | |
if (error.response.status === 401) { | |
try { | |
const rs = await api.get('/refresh', { | |
headers: { | |
Accept: 'application/json', | |
Authorization: `Bearer ${local_access_token}`, | |
}, | |
}); | |
const { access_token } = rs.data; | |
await AsyncStorage.setItem('@auth', JSON.stringify(rs.data)); | |
await AsyncStorage.setItem('@auth/token', access_token); | |
const originalConfig = error.config; | |
if (originalConfig) { | |
if (access_token) { | |
originalConfig.headers = { | |
...originalConfig.headers, | |
Authorization: `Bearer ${access_token}`, | |
}; | |
} | |
return new Promise((resolve, reject) => { | |
axios | |
.request(originalConfig) | |
.then(response => { | |
resolve(response); | |
}) | |
.catch(_error => { | |
reject(_error); | |
}); | |
}); | |
} else { | |
return; | |
} | |
} catch (_error) { | |
return Promise.reject(_error); | |
} | |
} | |
} | |
return Promise.reject(error); | |
}, | |
); | |
export default api; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment