update: route
This commit is contained in:
@@ -1,127 +1,92 @@
|
||||
import axios from 'axios';
|
||||
import Swal from 'sweetalert2';
|
||||
import axios from "axios";
|
||||
import Swal from "sweetalert2";
|
||||
|
||||
async function ApiRequest(
|
||||
urlParams = { method: 'GET', params: {}, url: '', prefix: '/', token: true }
|
||||
) {
|
||||
const baseURLDef = `${import.meta.env.VITE_API_SERVER}`;
|
||||
const instance = axios.create({
|
||||
baseURL: urlParams.url ?? baseURLDef,
|
||||
async function ApiRequest({
|
||||
method = "GET",
|
||||
params = {},
|
||||
url = "",
|
||||
prefix = "/",
|
||||
token = true,
|
||||
} = {}) {
|
||||
const baseURL = url || import.meta.env.VITE_API_SERVER;
|
||||
const instance = axios.create({ baseURL });
|
||||
|
||||
const isFormData = params instanceof FormData;
|
||||
|
||||
// request config
|
||||
const request = {
|
||||
method,
|
||||
url: prefix,
|
||||
data: params,
|
||||
headers: {
|
||||
"Accept-Language": "en_US",
|
||||
...(isFormData ? {} : { "Content-Type": "application/json" }),
|
||||
},
|
||||
};
|
||||
|
||||
// handle download (doc)
|
||||
if (params === "doc") {
|
||||
request.responseType = "blob";
|
||||
}
|
||||
|
||||
// ambil token
|
||||
const rawToken =
|
||||
sessionStorage.getItem("token_redirect") || localStorage.getItem("token");
|
||||
|
||||
if (token && rawToken) {
|
||||
const cleanToken = rawToken.replace(/"/g, "");
|
||||
instance.defaults.headers.common[
|
||||
"Authorization"
|
||||
] = `Bearer ${cleanToken}`;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await instance(request);
|
||||
return { ...response, error: false };
|
||||
} catch (error) {
|
||||
const status = error?.response?.status || 500;
|
||||
const message =
|
||||
error?.response?.data?.message || error.message || "Something Wrong";
|
||||
|
||||
cekError(status, message);
|
||||
return { ...error.response, error: true };
|
||||
}
|
||||
}
|
||||
|
||||
// global error handler
|
||||
async function cekError(status, message = "") {
|
||||
console.log("status code", status);
|
||||
|
||||
if (status === 401) {
|
||||
Swal.fire({
|
||||
icon: "warning",
|
||||
title: "Peringatan",
|
||||
text: `${message}, Silahkan login`,
|
||||
}).then((result) => {
|
||||
if (result.isConfirmed) {
|
||||
localStorage.clear();
|
||||
location.replace("/signin");
|
||||
}
|
||||
});
|
||||
|
||||
const isFormData = urlParams.params instanceof FormData;
|
||||
|
||||
const request = {
|
||||
method: urlParams.method,
|
||||
url: urlParams.prefix ?? '/',
|
||||
data: urlParams.params,
|
||||
// yang lama
|
||||
// headers: {
|
||||
// 'Content-Type': 'application/json',
|
||||
// 'Accept-Language': 'en_US',
|
||||
// },
|
||||
|
||||
// yang baru
|
||||
headers: {
|
||||
'Accept-Language': 'en_US',
|
||||
...(isFormData ? {} : { 'Content-Type': 'application/json' }),
|
||||
},
|
||||
};
|
||||
|
||||
if (urlParams.params === 'doc') {
|
||||
request.responseType = 'arraybuffer';
|
||||
request.headers['Content-Type'] = 'blob';
|
||||
}
|
||||
|
||||
// console.log(request);
|
||||
|
||||
// console.log('prefix', urlParams.prefix);
|
||||
|
||||
const tokenRedirect = sessionStorage.getItem('token_redirect');
|
||||
|
||||
let stringToken = '';
|
||||
|
||||
if (tokenRedirect !== null) {
|
||||
stringToken = tokenRedirect;
|
||||
// console.log(`sessionStorage: ${tokenRedirect}`);
|
||||
} else {
|
||||
stringToken = localStorage.getItem('token');
|
||||
// console.log(`localStorage: ${stringToken}`);
|
||||
}
|
||||
|
||||
if (urlParams.prefix !== 'auth/login') {
|
||||
const tokenWithQuotes = stringToken;
|
||||
const token = tokenWithQuotes.replace(/"/g, '');
|
||||
const AUTH_TOKEN = `Bearer ${token}`;
|
||||
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
|
||||
} else if (urlParams.token == true) {
|
||||
const tokenWithQuotes = stringToken;
|
||||
const token = tokenWithQuotes.replace(/"/g, '');
|
||||
const AUTH_TOKEN = `Bearer ${token}`;
|
||||
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
|
||||
}
|
||||
|
||||
return await instance(request)
|
||||
.then(function (response) {
|
||||
const responseCustom = response;
|
||||
responseCustom.error = false;
|
||||
return responseCustom;
|
||||
})
|
||||
.catch(function (error) {
|
||||
console.log('error', error.toJSON());
|
||||
|
||||
const errorData = error.toJSON();
|
||||
|
||||
const respError = error.response ?? {};
|
||||
cekError(
|
||||
errorData.status,
|
||||
error?.response?.data?.message ?? errorData?.message ?? 'Something Wrong'
|
||||
);
|
||||
respError.error = true;
|
||||
return respError;
|
||||
});
|
||||
}
|
||||
|
||||
async function cekError(props, message = '') {
|
||||
console.log('status code', props);
|
||||
if (props === 401) {
|
||||
Swal.fire({
|
||||
icon: 'warning',
|
||||
title: 'Peringatan',
|
||||
text: `${message}, Silahkan login`,
|
||||
}).then((result) => {
|
||||
if (result.isConfirmed) {
|
||||
localStorage.clear();
|
||||
location.replace('/signin');
|
||||
} else if (result.isDenied) {
|
||||
Swal.fire('Changes are not saved', '', 'info');
|
||||
}
|
||||
});
|
||||
} else {
|
||||
Swal.fire({
|
||||
icon: 'warning',
|
||||
title: 'Peringatan',
|
||||
text: message,
|
||||
}).then((result) => {});
|
||||
}
|
||||
} else {
|
||||
Swal.fire({
|
||||
icon: "warning",
|
||||
title: "Peringatan",
|
||||
text: message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// wrapper biar frontend lebih simple
|
||||
const SendRequest = async (queryParams) => {
|
||||
try {
|
||||
const response = await ApiRequest(queryParams);
|
||||
return response || [];
|
||||
} catch (error) {
|
||||
console.log('error', error);
|
||||
if (error.response) {
|
||||
console.error('Error Status:', error.response.status); // Status error, misal: 401
|
||||
console.error('Error Data:', error.response.data); // Detail pesan error
|
||||
console.error('Error Pesan:', error.response.data.message); //Pesan error
|
||||
} else {
|
||||
console.error('Error:', error.message);
|
||||
}
|
||||
Swal.fire({ icon: 'error', text: error });
|
||||
// return error;
|
||||
}
|
||||
try {
|
||||
const response = await ApiRequest(queryParams);
|
||||
return response?.data || [];
|
||||
} catch (error) {
|
||||
console.error("Request error:", error);
|
||||
Swal.fire({ icon: "error", text: error.message || "Something went wrong" });
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export { ApiRequest, SendRequest };
|
||||
|
||||
Reference in New Issue
Block a user