Add component

This commit is contained in:
2025-09-17 12:17:14 +07:00
parent b25aaf124c
commit 4a3ae20b84
19 changed files with 2074 additions and 0 deletions

View File

@@ -0,0 +1,127 @@
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,
});
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) => {});
}
}
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;
}
};
export { ApiRequest, SendRequest };