SHARE
TWEET

Untitled

a guest Aug 20th, 2019 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. axios.defaults.baseURL = localStorage.getItem('domain');
  2.  
  3. let isRefreshing = false;
  4. let failedQueue = [];
  5.  
  6. const processQueue = (error, token = null) => {
  7.   failedQueue.forEach(prom => {
  8.     if (error) {
  9.       prom.reject(error);
  10.     } else {
  11.       prom.resolve(token);
  12.     }
  13.   })
  14.   failedQueue = [];
  15. }
  16.  
  17. axios.interceptors.response.use(function (response) {
  18.   document.body.classList.remove('loading-indicator');
  19.  
  20.   return response;
  21. }, error => {
  22.  
  23.   const originalRequest = error.config;
  24.  
  25.   if (error.response.status === 401 && !originalRequest._retry) {    
  26.     if (isRefreshing) {
  27.       return new Promise((resolve, reject) => {
  28.         failedQueue.push({resolve, reject})
  29.       }).then(token => {
  30.         originalRequest.headers["Authorization"] = "Bearer " + token;
  31.         return axios(originalRequest);
  32.       }).catch(err => {
  33.         return Promise.reject(err);
  34.       })
  35.     }
  36.  
  37.     originalRequest._retry = true;
  38.     isRefreshing = true;
  39.  
  40.     const data = qs.stringify({
  41.       grant_type: "refresh_token",
  42.       client_id: "****",
  43.       client_secret: "******",
  44.       refresh_token: window.localStorage.getItem("token")
  45.     const config = {
  46.       headers: {
  47.         "Content-Type": "application/x-www-form-urlencoded"
  48.       }
  49.     }
  50.  
  51.     return new Promise(function (resolve, reject) {
  52.       axios({
  53.         method: "post",
  54.         url: "/oauth2/token",
  55.         data,
  56.         config
  57.       })
  58.       .then(({data}) => {
  59.         const token = data;
  60.  
  61.       })
  62.       .catch((err) => {
  63.         processQueue(err, null);
  64.         reject(err);
  65.       })
  66.       .then(() => { isRefreshing = false })
  67.     })
  68.   }
  69.  
  70.   return Promise.reject(error);
  71. });
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top