frontend-apt

Untitled

Jun 22nd, 2022 (edited)
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { store } from '@/store'
  2. import { addNotification } from '@/store/slices/NotificationSlice'
  3. import { clearUserData } from '@/store/slices/User'
  4. import axios from 'axios'
  5. import Router from 'next/router'
  6. import { setupCache } from 'axios-cache-interceptor'
  7.  
  8.  
  9. const axiosInstance = axios.create()
  10. const cacheOptions = {
  11.   ttl: 1000 * 60 * 5,
  12.   debug: (message) => {
  13.     // Etc
  14.     console.log(message)
  15.   },
  16. }
  17. const AXIOS = setupCache(axiosInstance, cacheOptions)
  18. AXIOS.defaults.baseURL = process.env.NEXT_PUBLIC_API_URL
  19. console.log(setupCache)
  20.  
  21. export const AXIOS_SET_AUTH_TOKEN = (token) => {
  22.   AXIOS.defaults.headers.common.Authorization = "Bearer "+token
  23. }
  24.  
  25. AXIOS.interceptors.response.use(
  26.   function (response) {
  27.     if (response.config.notification) {
  28.       store.dispatch(
  29.         addNotification({
  30.           type: 'success',
  31.           message: response.data.message,
  32.         })
  33.       )
  34.     }
  35.     return {
  36.       res: response.data.data,
  37.       status: true,
  38.     }
  39.   },
  40.   function (error) {
  41.     store.dispatch(
  42.       addNotification({
  43.         type: 'error',
  44.         message: error.response.data.message,
  45.       })
  46.     )
  47.  
  48.     if (error.response.status === '401' || error.response.status === 401) {
  49.       store.dispatch(clearUserData())
  50.       AXIOS_SET_AUTH_TOKEN('')
  51.       Router.push('/login')
  52.     }
  53.  
  54.     return {
  55.       res: error.response,
  56.       status: false,
  57.     }
  58.   }
  59. )
  60.  
  61. export default AXIOS
Add Comment
Please, Sign In to add comment