Untitled
unknown
typescript
2 days ago
3.1 kB
6
Indexable
Never
import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios'; interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig { _retry?: boolean; } const authUrl = process.env.NEXT_PUBLIC_URL; const clientId = process.env.NEXT_PUBLIC_CLIENT_ID; const clientSecret = process.env.NEXT_PUBLIC_CLIENT_SECRET; const grantType = 'client_credentials'; let isRefreshing = false; let failedQueue: { resolve: (token: string) => void; reject: (error: any) => void }[] = []; const processQueue = (error: any, token: string | null = null) => { failedQueue.forEach(prom => { if (error) { prom.reject(error); console.log('dua') } else { console.log('satu') prom.resolve(token as string); } }); failedQueue = []; }; const axiosInstance = axios.create({ baseURL: authUrl, }); // Interceptor untuk request axiosInstance.interceptors.request.use( (config: CustomAxiosRequestConfig) => { const token = localStorage.getItem('accessToken'); if (token) { config.headers.Authorization = `Bearer ${token}/oauth/token`; } return config; }, (error: AxiosError) => Promise.reject(error) ); // Interceptor untuk response axiosInstance.interceptors.response.use( (response: AxiosResponse) => response, async (error: AxiosError) => { const originalRequest = error.config as CustomAxiosRequestConfig; // Gunakan CustomAxiosRequestConfig // Pastikan originalRequest tidak undefined sebelum melanjutkan if (error.response?.status === 401 && originalRequest && !originalRequest._retry) { if (isRefreshing) { return new Promise((resolve, reject) => { failedQueue.push({ resolve, reject }); }) .then((token) => { originalRequest.headers.Authorization = `Bearer ${token}`; return axiosInstance(originalRequest); }) .catch((err) => Promise.reject(err)); } originalRequest._retry = true; // Set _retry menjadi true untuk menandakan request sudah diulang isRefreshing = true; try { // Request untuk mendapatkan token baru const { data } = await axios.post(`${authUrl}`, { grant_type: grantType, client_id: clientId, client_secret: clientSecret, }, { headers: { 'Content-Type': 'application/json', } }); // Simpan token yang baru didapatkan ke localStorage localStorage.setItem('accessToken', data.access_token); console.log('token', data.access_token); // Proses queue dan jalankan ulang request yang gagal axiosInstance.defaults.headers.common.Authorization = `Bearer ${data.access_token}`; processQueue(null, data.access_token); // Jalankan ulang request asli yang gagal return axiosInstance(originalRequest); } catch (err) { processQueue(err, null); return Promise.reject(err); } finally { isRefreshing = false; } } return Promise.reject(error); } ); export default axiosInstance;
Leave a Comment