Untitled

mail@pastecode.io avatar
unknown
javascript
2 months ago
1.9 kB
2
Indexable
Never
// router and axios
import axios from 'axios'

// variables
const baseURL = process.env.NEXT_PUBLIC_HOST

// create axios call
const api_client = axios.create({
    baseURL: baseURL,
})

const fetcher = url => api_client.get(url).then(res => res.data)

// axios request (add token to headers)
api_client.interceptors.request.use(
    async config => {
        let token = localStorage.getItem('access_token') ? localStorage.getItem('access_token') : null
        config.headers = { 'Authorization': `Bearer ${token}` }
        return config
    },
    error => {
        Promise.reject(error)
    });

// axios response (refresh token or logout)
api_client.interceptors.response.use(
    (res) => {
        return res
    },
    async (error) => {
        if (error.response.status === 401) {
            const refresh_token = localStorage.getItem('refresh_token') ? localStorage.getItem('refresh_token') : null
            if (refresh_token !== null) {
                await axios.post(`${baseURL}api/token/refresh/`, { refresh: refresh_token }).then(response => {
                    if (response.status === 200) {
                        localStorage.clear()
                        localStorage.setItem('access_token', response.data.access)
                        localStorage.setItem('refresh_token', response.data.refresh)
                        return api_client(error.config)
                    } else {
                        localStorage.clear()
                        console.log(response);
                        window.location.href = `/login`;
                    }
                }).catch(error => {
                    console.log(error);
                    localStorage.clear()
                    window.location.href = `/login`;
                });
            }
        }
        return Promise.reject(error)
    }
)

export { api_client, fetcher }
Leave a Comment