Files
ProcureLinc-Mobile-App/src/Axios/Axios.ts
T

109 lines
2.8 KiB
TypeScript

import axios from 'axios';
import { setToken } from '../Redux/Slices/Token';
import { store } from '../Redux/Store';
export const apiCall = async <R, D = {}>(
method: 'get' | 'post' | 'patch' | 'delete' | 'put',
url: string,
data?: D,
params?: any,
contentType?: string
): Promise<R> => {
const token: any = store.getState().token.token;
// 🔥 ONE MAIN GROUP FOR ENTIRE API CALL
console.group(
`%c🚀 API CALL → ${method.toUpperCase()} ${url}`,
'color:#0ea5e9;font-weight:bold'
);
// ===== REQUEST =====
console.group('📤 REQUEST');
console.log('%cMETHOD →', 'color:#22c55e;font-weight:bold', method);
console.log('%cURL →', 'color:#22c55e;font-weight:bold', url);
console.log('%cPARAMS →', 'color:#f59e0b;font-weight:bold', params);
console.log('%cPAYLOAD →', 'color:#a855f7;font-weight:bold', data);
console.log(
'%cTOKEN →',
'color:#ef4444;font-weight:bold',
token?.token ? '✔ PRESENT' : '❌ MISSING'
);
console.groupEnd();
try {
const response = await axios({
method,
url,
data,
params,
headers: {
Authentication: `Bearer ${token?.token}`,
'Content-Type': contentType || 'application/json',
},
});
// ===== RESPONSE =====
console.group('📥 RESPONSE');
console.log(
'%cSTATUS →',
'color:#22c55e;font-weight:bold',
response.status
);
console.log(
'%cRESPONSE DATA →',
'color:#0ea5e9;font-weight:bold',
response.data
);
console.groupEnd();
console.groupEnd(); // 🔚 MAIN GROUP
return response.data;
} catch (error: any) {
// ===== ERROR =====
console.group('❌ ERROR');
console.error(
'%cSTATUS →',
'color:#ef4444;font-weight:bold',
error?.response?.status
);
console.error(
'%cMESSAGE →',
'color:#f97316;font-weight:bold',
error?.response?.data?.message || error.message
);
console.error(
'%cERROR DATA →',
'color:#fb7185;font-weight:bold',
error?.response?.data
);
console.error(
'%cFULL ERROR →',
'color:#7c2d12;font-weight:bold',
error
);
console.groupEnd();
// ===== AUTH ERROR =====
if (error?.response?.status === 401) {
console.warn(
'%c⚠ JWT ERROR → Token expired or malformed',
'color:#eab308;font-weight:bold'
);
store.dispatch(setToken({}));
console.groupEnd(); // 🔚 MAIN GROUP
return {
success: false,
message: 'JWT Error - Token expired or malformed',
} as R;
}
console.groupEnd(); // 🔚 MAIN GROUP
return {
success: false,
message:
error?.response?.data?.message || 'No Response From Server',
...(error?.response?.data || {})
} as R;
}
};