Files
OSIT-AE-App-Svelte/src/lib/ae_api/api_patch_object.ts
2025-05-07 16:17:34 -04:00

91 lines
2.3 KiB
TypeScript

import axios from 'axios';
// Updated 2024-05-23
export let patch_object = async function patch_object(
{
api_cfg = null,
endpoint = '',
params = {},
data = {},
return_meta = false,
log_lvl = 2,
retry_count = 5 // Number of retry attempts
}: {
api_cfg: any,
endpoint: string,
params?: any,
data?: any,
return_meta?: boolean,
log_lvl?: number,
retry_count?: number
}
) {
if (log_lvl) {
console.log(`*** patch_object() *** Endpoint: ${endpoint}`);
console.log('Params:', params);
if (log_lvl > 1) {
console.log('Data:', data);
}
}
if (log_lvl) {
// console.log(api_cfg);
console.log(endpoint);
console.log(params);
if (log_lvl > 1) {
console.log(data);
}
// console.log(return_meta);
// console.log(as_list);
}
if (!api_cfg) {
console.error('No API Config was provided. Returning false.');
return false;
}
let axios_api = axios.create({
baseURL: api_cfg['base_url'],
/* other custom settings */
});
axios_api.defaults.headers = api_cfg['headers'];
for (let attempt = 1; attempt <= retry_count; attempt++) {
try {
const response = await axios_api.patch(endpoint, data, { params: params });
if (log_lvl) {
console.log(`Response: status=${response.status} attempt=${attempt}`);
}
if (log_lvl > 1) {
console.log('Response Data:', response.data);
}
// Return the response data
return response.data['data'];
} catch (error) {
if (log_lvl) {
console.error(`Error on attempt ${attempt}:`, error);
}
// Handle specific errors (e.g., 404)
if (error.response && error.response.status === 404) {
console.warn('404 Not Found. Returning null.');
return null; // Returning null since there were no results
}
// If this is the last attempt, return false
if (attempt === retry_count) {
console.error('Max retry attempts reached. Returning false.');
return false;
}
// Log retry information
if (log_lvl) {
console.log(`Retrying... (${attempt}/${retry_count})`);
}
}
}
// return response_data;
}