All files / lib axios.ts

55.55% Statements 10/18
70% Branches 7/10
100% Functions 3/3
52.94% Lines 9/17

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    66x         66x 428x 428x           12x       428x   389x 2x 2x                                                
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())
    }
 E }
  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 }