Created
August 20, 2019 13:37
-
-
Save tehSLy/fac443e83817db36f71cb3e370175485 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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