Files
mariani_mobile/utils/api.ts
leonardo 7c8ef45e5a feat: Update assets and improve code comments across multiple components
- Updated favicon and various image assets.
- Enhanced comments.
- Adjusted styles and functionality in several components for improved user experience.
- Updated package-lock.json to reflect dependency updates.
2026-02-06 12:56:34 +01:00

54 lines
1.6 KiB
TypeScript

import axios from 'axios';
import * as SecureStore from 'expo-secure-store';
const API_BASE_URL = process.env.EXPO_PUBLIC_API_URL;
export const KEY_TOKEN = 'auth_key';
// Create an Axios instance with default configuration
const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
timeout: 10000, // 10 seconds timeout
});
// Interceptor: Adds the token to EVERY request if it exists
api.interceptors.request.use(
async (config) => {
const token = await SecureStore.getItemAsync(KEY_TOKEN);
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
console.log(`[API REQUEST] ${config.method?.toUpperCase()} ${config.url}`);
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Interceptor: Global error handling (e.g., expired token)
api.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
if (error.response) {
console.error('[API ERROR]', error.response.status, error.response.data);
// If we receive 401 (Unauthorized), we might want to force logout
if (error.response.status === 401) {
// TODO: Here you can add logic to redirect to login screen if needed
await SecureStore.deleteItemAsync(KEY_TOKEN);
}
} else {
console.error('[API NETWORK ERROR]', error.message);
}
return Promise.reject(error);
}
);
export default api;