All files / lib axios.ts

30.55% Statements 11/36
25% Branches 5/20
33.33% Functions 2/6
33.33% Lines 9/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48    37x         37x 203x 203x           2x 1x     203x   171x         1x                                          
import axios from 'axios'
import { useAuthStore } from '@/features/auth/authStore'
import type { AxiosRequestConfig } from 'axios'
 
interface RetryConfig extends AxiosRequestConfig {
  _retry?: boolean
}
 
const apiClient = axios.create({
  baseURL: '/api/v1',
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
})
I
apiClient.interceptors.request.use((config) => {
  const method = config.method?.toLowerCase()
  if (method && ['post', 'put', 'patch', 'delete'].includes(method)) {
    if (!config.headers['Idempotency-Key']) {
      config.headers.set('Idempotency-Key', crypto.randomUUID())
    }
  }
  return config
})
 
apiClient.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response?.status !== 401 || (error.config as RetryConfig)?._retry) {
      return Promise.reject(error)
    }

    ;(error.config as RetryConfig)._retry = true
 
    try {
      await apiClient.post('/api/auth/refresh')
      return apiClient(error.config)
    } catch {
      useAuthStore.getState().clearAuth()
      window.location.href = '/#/login?expired=true'
      return Promise.reject(error)
    }
  },
)
 
export { apiClient }