37 lines
1010 B
TypeScript
37 lines
1010 B
TypeScript
import axios from "axios";
|
|
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
import { BASE_URL, STORAGE_KEYS } from "../constants/config";
|
|
import { router } from "expo-router";
|
|
|
|
const api = axios.create({
|
|
baseURL: BASE_URL,
|
|
timeout: 10000,
|
|
});
|
|
|
|
//Request interceptor to add auth token
|
|
api.interceptors.request.use(async (config) => {
|
|
const token = await AsyncStorage.getItem(STORAGE_KEYS.AUTH_TOKEN);
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
return config;
|
|
});
|
|
|
|
//Response interceptor to handle errors
|
|
api.interceptors.response.use(
|
|
(response) => response,
|
|
async (error) => {
|
|
const status = error.response?.status;
|
|
//if token is expired or not present, clear it from storage
|
|
if (status === 401 || status === 403) {
|
|
console.log("Token expired or not present");
|
|
await AsyncStorage.removeItem(STORAGE_KEYS.AUTH_TOKEN);
|
|
router.replace("/auth/login");
|
|
}
|
|
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default api;
|