Skip to content

Instantly share code, notes, and snippets.

@tehSLy
Created August 20, 2019 13:37
Show Gist options
  • Select an option

  • Save tehSLy/fac443e83817db36f71cb3e370175485 to your computer and use it in GitHub Desktop.

Select an option

Save tehSLy/fac443e83817db36f71cb3e370175485 to your computer and use it in GitHub Desktop.
const createConnectionModel = (config: any, refreshURL: string) => {
const instance = axios.create(config);
let refreshRequest: Promise<any>;
const unauthorized = createEvent();
/* если юзаете JWT без кук, что впрочем, я не рекомендую
instance.interceptors.request.use((config) => {
config.headers['auth'] = localStorage.getItem(...);
})
*/
instance.interceptors.response.use(null, async (err: AxiosError) => {
if(Number(err.code) === 401){
if(!refreshRequest){
refreshRequest = instance.get(refreshURL);
}
await refreshRequest.catch(unauthorized);
return instance({...err.config, baseURL: ""})// иначе, baseURL прилепится дважды
}
})
return {instance, unauthorized}
};
const {instance, unauthorized} = createConnectionModel({}, "/api/refresh_token");
unauthorized.watch(() => history.push('/login'));
instance.get('/api/user/current');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment