Created
August 20, 2020 09:44
-
-
Save absk1317/330fd91807d2e05e00cee9a0a4237dad to your computer and use it in GitHub Desktop.
Axios interceptor
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 from 'axios'; | |
import configureStore from './Store'; | |
const { store } = configureStore(); | |
const instance = axios.create({ | |
headers: { | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
} | |
}); | |
instance.interceptors.request.use( | |
async config => { | |
const token = await store.getState().Auth.accessToken; | |
config.metadata = { startTime: new Date() }; | |
if (token) { | |
config.headers.Authorization = `Bearer ${token}`; | |
} | |
return config; | |
}, | |
error => Promise.reject(error) | |
); | |
instance.interceptors.response.use( | |
response => { | |
let duration = new Date() - response.config.metadata.startTime; | |
response.duration = duration; | |
let weakInternet = response.config.method == 'get' && response.duration > 1200; | |
if (weakInternet) { | |
try { | |
let contentSize = JSON.stringify(response.data).replace(/[\[\]\,\"]/g, '').length / 1000; | |
// if content size divided by duration for api call i.e bytes/miliSecond | |
// or say (bytes/1000)/(duration/1000) which is KBps is greater than 50KBps, its not weak | |
weakInternet = contentSize / (duration / 1000) < 50; | |
} catch (error) {} | |
} | |
PubSub. publishSync(MESSAGE_TOPICS.LOW_NETWORK, { weakInternet }, 'Success'); | |
return response; | |
}, | |
error => { | |
return Promise.reject(error); | |
} | |
); | |
export default instance; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment