89 lines
2.3 KiB
TypeScript
89 lines
2.3 KiB
TypeScript
'use server';
|
|
import { env } from '@/lib/env';
|
|
import axios, { InternalAxiosRequestConfig } from 'axios';
|
|
import { z } from 'zod';
|
|
|
|
// Crear instancia de Axios con la URL base validada
|
|
const fetchApi = axios.create({
|
|
baseURL: env.API_URL,
|
|
});
|
|
|
|
// Interceptor para incluir el token automáticamente en las peticiones
|
|
// ESTE INTERCEPTOR ESTÁ BIEN PARA EL RESTO DE LAS PETICIONES AUTENTICADAS
|
|
fetchApi.interceptors.request.use(
|
|
async (config: InternalAxiosRequestConfig) => {
|
|
try {
|
|
const { getValidAccessToken } = await import('@/lib/auth-token');
|
|
const token = await getValidAccessToken();
|
|
|
|
if (token) {
|
|
config.headers.set('Authorization', `Bearer ${token}`);
|
|
}
|
|
} catch (err) {
|
|
console.error('Error getting auth token:', err);
|
|
}
|
|
return config;
|
|
},
|
|
);
|
|
|
|
// safeFetchApi sigue siendo útil para el resto de las llamadas que requieren autenticación
|
|
export const safeFetchApi = async <T extends z.ZodSchema<any>>(
|
|
schema: T,
|
|
url: string,
|
|
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' = 'GET',
|
|
data?: any,
|
|
): Promise<
|
|
[{ type: string; message: string; details?: any } | null, z.infer<T> | null]
|
|
> => {
|
|
try {
|
|
const response = await fetchApi({
|
|
method,
|
|
url,
|
|
data,
|
|
});
|
|
|
|
const parsed = schema.safeParse(response.data);
|
|
|
|
if (!parsed.success) {
|
|
console.error('Validation Error Details:', {
|
|
errors: parsed.error.errors,
|
|
receivedData: response.data,
|
|
expectedSchema: schema,
|
|
data: response.data.data,
|
|
});
|
|
return [
|
|
{
|
|
type: 'VALIDATION_ERROR',
|
|
message: 'Validation error',
|
|
details: parsed.error.errors,
|
|
},
|
|
null,
|
|
];
|
|
}
|
|
|
|
return [null, parsed.data];
|
|
} catch (error: any) {
|
|
const errorDetails = {
|
|
status: error.response?.status,
|
|
statusText: error.response?.statusText,
|
|
message: error.message,
|
|
url: error.config?.url,
|
|
method: error.config?.method,
|
|
requestData: error.config?.data,
|
|
responseData: error.response?.data,
|
|
headers: error.config?.headers,
|
|
};
|
|
|
|
return [
|
|
{
|
|
type: 'API_ERROR',
|
|
message: error.response?.data?.message || 'Unknown API error',
|
|
details: errorDetails,
|
|
},
|
|
null,
|
|
];
|
|
}
|
|
};
|
|
|
|
export { fetchApi };
|