Delete will now retry and no longer needs Axios. Code clean up. Bug fix when deleting a Journal Entry.

This commit is contained in:
Scott Idem
2025-05-07 18:12:43 -04:00
parent 86221e6aec
commit 2ff7b4fd70
4 changed files with 125 additions and 52 deletions

View File

@@ -1,63 +1,133 @@
import axios from 'axios'; // import axios from 'axios';
// Updated 2024-05-23 // Updated 2024-05-23
export let delete_object = async function delete_object( export let delete_object = async function delete_object(
{ {
api_cfg=null, api_cfg = null,
endpoint='', endpoint = '',
params={}, params = {},
data={}, data = {},
return_meta=false, return_meta = false,
log_lvl=0 log_lvl = 0,
retry_count = 5 // Number of retry attempts
}: { }: {
api_cfg: any, api_cfg: any,
endpoint: string, endpoint: string,
params?: any, params?: any,
data?: any, data?: any,
return_meta?: boolean, return_meta?: boolean,
log_lvl?: number log_lvl?: number,
retry_count?: number
} }
) { ) {
console.log('*** delete_object() ***'); if (log_lvl) {
console.log(`*** delete_object() *** Endpoint: ${endpoint}`);
console.log('Params:', params);
if (log_lvl > 1) {
console.log('Data:', data);
}
}
if (!api_cfg) {
console.error('No API Config was provided. Returning false.');
return false;
}
// Construct the URL with query parameters
const url = new URL(endpoint, api_cfg['base_url']);
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
// Clean the headers
let headers_cleaned: Record<string, string> = {};
for (const prop in api_cfg['headers']) {
let prop_cleaned = prop.replaceAll('_', '-');
headers_cleaned[prop_cleaned] = api_cfg['headers'][prop];
}
if (log_lvl) {
// console.log(api_cfg);
console.log(endpoint);
console.log(params);
if (log_lvl > 1) { if (log_lvl > 1) {
console.log('Data:', data); console.log('Cleaned Headers:', headers_cleaned);
console.log(typeof data);
} }
// console.log(return_meta);
// console.log(as_list);
}
// https://stackoverflow.com/questions/51069552/axios-delete-request-with-body-and-headers const fetchOptions: RequestInit = {
method: 'DELETE',
headers: {
...headers_cleaned,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
let axios_api = axios.create({ if (log_lvl > 1) {
baseURL: api_cfg['base_url'], console.log('Fetch Options:', fetchOptions);
// timeout: 2000,
/* other custom settings */
});
axios_api.defaults.headers = api_cfg['headers'];
//OLD: axios_api.delete(endpoint, { 'data': data })
let response_data = await axios_api.delete(endpoint, { params: params, 'data': data })
.then(function (response) {
console.log(response.data);
return response.data;
})
.catch(function (error) {
if (error.response && error.response.status === 404) {
return null; // Returning null since there were no results
} }
console.log(error);
return false; // Returning false since something may have gone wrong. Also more in line with what the API returns.
// return error;
});
if (log_lvl > 1) { for (let attempt = 1; attempt <= retry_count; attempt++) {
console.log(response_data); try {
} const response = await fetch(url.toString(), fetchOptions);
return response_data;
if (log_lvl) {
console.log(`Response: status=${response.status} attempt=${attempt}`);
}
if (!response.ok) {
if (response.status === 404) {
console.warn('404 Not Found. Returning null.');
return null; // Returning null since there were no results
}
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
if (log_lvl > 1) {
console.log('Response JSON:', json);
}
// Return the response data or metadata
return return_meta ? json : json.data;
} catch (error) {
console.error(`API DELETE error on attempt ${attempt}:`, error);
// 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})`);
}
}
}
// https://stackoverflow.com/questions/51069552/axios-delete-request-with-body-and-headers
// let axios_api = axios.create({
// baseURL: api_cfg['base_url'],
// // timeout: 2000,
// /* other custom settings */
// });
// axios_api.defaults.headers = api_cfg['headers'];
// //OLD: axios_api.delete(endpoint, { 'data': data })
// let response_data = await axios_api.delete(endpoint, { params: params, 'data': data })
// .then(function (response) {
// console.log(response.data);
// return response.data;
// })
// .catch(function (error) {
// if (error.response && error.response.status === 404) {
// return null; // Returning null since there were no results
// }
// console.log(error);
// return false; // Returning false since something may have gone wrong. Also more in line with what the API returns.
// // return error;
// });
// if (log_lvl > 1) {
// console.log(response_data);
// }
// return response_data;
} }

View File

@@ -189,12 +189,17 @@ export let get_object = async function get_object(
} }
} }
} catch (error) { } catch (error) {
// if (log_lvl) { console.log(`API GET object request *fetch* error on attempt ${attempt}:`, error);
console.log(`API GET object request *fetch* error on attempt ${attempt}:`, error);
// }
if (attempt === retry_count) { if (attempt === retry_count) {
console.log('Max retry attempts reached. Returning false.');
return false; return false;
} }
// Log retry information
if (log_lvl) {
console.log(`Retrying... (${attempt}/${retry_count})`);
}
} }
} }
}; };

View File

@@ -86,9 +86,7 @@ export let patch_object = async function patch_object(
// Return the response data or metadata // Return the response data or metadata
return return_meta ? json : json.data; return return_meta ? json : json.data;
} catch (error) { } catch (error) {
// if (log_lvl) { console.error(`API PATCH error on attempt ${attempt}:`, error);
console.error(`API PATCH error on attempt ${attempt}:`, error);
// }
// If this is the last attempt, return false // If this is the last attempt, return false
if (attempt === retry_count) { if (attempt === retry_count) {

View File

@@ -1110,9 +1110,9 @@ function handle_cut_string(old_string: string) {
console.error('Error deleting journal entry:', error); console.error('Error deleting journal entry:', error);
alert('Failed to delete journal entry.'); alert('Failed to delete journal entry.');
}).finally(() => { }).finally(() => {
$journals_slct.journal_id = null; goto(`/journals/${$journals_slct.journal_id}`);
$journals_slct.journal_obj = null; // $journals_slct.journal_id = null;
goto(`/journals/${$lq__journal_entry_obj?.journal_id}`); // $journals_slct.journal_obj = null;
}); });
} }
}} }}