All files / core/lib api.ts

100% Statements 32/32
88% Branches 22/25
100% Functions 4/4
100% Lines 32/32

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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65      14x   14x             14x 3x 3x   3x 1x 2x 1x   3x     14x 1x   3x   3x     3x 2x 2x 2x   2x 2x 1x   1x       1x 1x 1x       3x       14x 4x 2x   2x 1x   1x    
import axios from 'axios'
import { STORAGE_KEYS } from './constants'
 
export const VITE_API_URL = import.meta.env.VITE_API_URL || '/api'
 
export const api = axios.create({
    baseURL: VITE_API_URL,
    headers: {
        'Content-Type': 'application/json',
    },
})
 
api.interceptors.request.use((config) => {
    const token = localStorage.getItem(STORAGE_KEYS.TOKEN)
    const staffToken = localStorage.getItem(STORAGE_KEYS.STAFF_TOKEN)
 
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    } else if (staffToken) {
        config.headers.Authorization = `Bearer ${staffToken}`
    }
    return config
})
 
api.interceptors.response.use(
    (response) => response,
    (error) => {
        Eif (error.response?.status === 401) {
            const isStaffPath =
                window.location.pathname.includes('/staff') &&
                !window.location.pathname.startsWith('/admin')
 
            if (isStaffPath) {
                Eif (!window.location.pathname.includes('/login')) {
                    localStorage.removeItem(STORAGE_KEYS.STAFF_TOKEN)
                    localStorage.removeItem(STORAGE_KEYS.STAFF_USER)
                    // Find slug in path - assuming /:slug/staff/...
                    const match = window.location.pathname.match(/\/([^/]+)\/staff/)
                    if (match) {
                        window.location.href = `/${match[1]}/staff/login`
                    } else {
                        window.location.href = '/'
                    }
                }
            } else {
                Eif (!window.location.pathname.includes('/login')) {
                    localStorage.removeItem(STORAGE_KEYS.TOKEN)
                    window.location.href = '/login'
                }
            }
        }
        return Promise.reject(error)
    },
)
 
export const getApiErrorMessage = (error: unknown, defaultMessage = 'Request failed'): string => {
    if (axios.isAxiosError(error)) {
        return error.response?.data?.message || error.message
    }
    if (error instanceof Error) {
        return error.message
    }
    return defaultMessage
}