ÿØÿà JFIF ` ` ÿþ
|
Server : Apache System : Linux cloud.heroica.com.br 4.18.0-553.36.1.el8_10.x86_64 #1 SMP Wed Jan 22 03:07:54 EST 2025 x86_64 User : farolpborg ( 1053) PHP Version : 7.4.33 Disable Function : exec,passthru,shell_exec,system Directory : /var/www/node_services/sebrae_test_admin/src/utils/ |
Upload File : |
import axios from 'axios';
import { logout } from "../contexts/UserContext";
import { parseCookies } from "nookies";
import { toast } from 'react-toastify';
import {loadingBus} from "./loadingBus";
function setupapi(context: any = undefined) {
const cookies = parseCookies(context);
const token = cookies['@sebraeappvisita.token'];
const apiaxios = axios.create({
baseURL: import.meta.env.VITE_BACKEND_URL,
headers: {
Authorization: `Bearer ${token}`
}
});
// Loading bus is required lazily to avoid circular deps
apiaxios.interceptors.request.use((config) => {
try { loadingBus.inc(); } catch {}
return config;
}, (error) => {
try { loadingBus.dec(); } catch {}
return Promise.reject(error);
});
apiaxios.interceptors.response.use(
(response) => {
// Show success toast for POST and PUT requests
const method = (response.config.method || '').toLowerCase();
if (method === 'post' || method === 'put') {
// Try to use a message from the API, otherwise fall back to a generic one
const apiMsg = (response.data && (response.data.message || response.data.success)) as string | undefined;
const msg = apiMsg || (method === 'post' ? 'Registro criado com sucesso' : 'Registro atualizado com sucesso');
toast.success(msg);
}
try { loadingBus.dec(); } catch {}
return response;
},
(error) => {
const status = error?.response?.status;
const apiMessage = error?.response?.data?.message || error?.response?.data?.error;
const message = apiMessage || (status === 401 ? 'Sessão expirada. Faça login novamente.' : 'Erro ao comunicar com o servidor.');
// Show error toast for any API error
toast.error(message);
if (status === 401) {
// attempt logout on unauthorized
logout().catch((err: any) => {
console.log('erro logout', err);
});
}
try { loadingBus.dec(); } catch {}
// Always reject to propagate error to callers
return Promise.reject(error);
}
);
return apiaxios;
}
export default setupapi