Last active
August 8, 2019 10:29
-
-
Save tehSLy/4d734f95deb9322c4d99d78152268a33 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: AxiosRequestConfig, refreshURL: string) => { | |
| const unauthenticated = createEvent(); | |
| let refreshRequest: Promise<any>; | |
| const connection = axios.create(config); | |
| connection.interceptors.response.use(null, async (err) => { | |
| if(err.response.code === 401){ | |
| if(err.response.data === "Unauthenticated"){ | |
| unauthenticated(); | |
| throw new Error("unauthenticated"); | |
| } | |
| if(!refreshRequest){ | |
| refreshRequest = connection.post(refreshURL); | |
| refreshRequest.catch(unauthenticated); //if token refresh did fail | |
| } | |
| const response = await refreshRequest; | |
| if(!response){ //handle situation when token did not refresh | |
| return null; | |
| } | |
| refreshRequest = null; | |
| return connection.request({...err.config, baseURL: ""}); //retrying source request | |
| } | |
| }); | |
| return { | |
| connection, | |
| unauthenticated | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment