Skip to content

Instantly share code, notes, and snippets.

@tehSLy
Last active August 8, 2019 10:29
Show Gist options
  • Select an option

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

Select an option

Save tehSLy/4d734f95deb9322c4d99d78152268a33 to your computer and use it in GitHub Desktop.
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