Refactor core API helpers and implement System Testing Dashboard

- Unified and hardened get, post, patch, and delete helpers with standardized retry logic, kebab-case headers, and V3 response envelope handling.
- Implemented robust 'Bootstrap Paradox' resolution logic across the API stack to handle unauthenticated site domain lookups safely.
- Enhanced API helpers to support custom fetch injection, enabling reliable server-side execution in SvelteKit.
- Upgraded /testing page into a comprehensive System Testing Dashboard for core helper and V3 search verification.
- Updated TODO.md and GEMINI.md with 2026-01-08 session learnings and 'Frontier Journals' vision.
This commit is contained in:
Scott Idem
2026-01-08 11:30:05 -05:00
parent bc56b38ec1
commit e355b7649d
8 changed files with 548 additions and 897 deletions

View File

@@ -1,19 +1,27 @@
// import axios from 'axios';
import type { key_val } from '$lib/stores/ae_stores';
// Updated 2024-05-23
/**
* Performs a DELETE request to the Aether API.
* Refactored 2026-01-08 to use standard fetch with timeout, custom fetch injection,
* standardized kebab-case headers, and robust V3 response handling.
*/
export const delete_object = async function delete_object({
api_cfg = null,
endpoint = '',
headers = {},
params = {},
data = {},
timeout = 60000,
return_meta = false,
log_lvl = 0,
retry_count = 5 // Number of retry attempts
retry_count = 5
}: {
api_cfg: any;
endpoint: string;
headers?: any;
params?: any;
data?: any;
timeout?: number;
return_meta?: boolean;
log_lvl?: number;
retry_count?: number;
@@ -23,6 +31,7 @@ export const delete_object = async function delete_object({
console.log('Params:', params);
if (log_lvl > 1) {
console.log('Data:', data);
console.log(`Base URL: ${api_cfg?.['base_url']}`);
}
}
@@ -33,35 +42,83 @@ export const delete_object = async function delete_object({
// 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]));
if (params) {
Object.keys(params).forEach((key) => url.searchParams.append(key, params[key]));
}
// Clean the headers
const headers_cleaned: Record<string, string> = {};
for (const prop in api_cfg['headers']) {
// Clean and merge headers without mutating the original api_cfg
const headers_cleaned: key_val = {};
const merged_headers = { ...api_cfg['headers'], ...headers };
// Handle "Bootstrap Paradox" for unauthenticated requests
if (merged_headers.hasOwnProperty('x-no-account-id')) {
delete merged_headers['x-account-id'];
if (merged_headers['x-no-account-id'] === null) {
merged_headers['x-no-account-id'] = 'Nothing to See Here';
}
}
for (const prop in merged_headers) {
const prop_cleaned = prop.replaceAll('_', '-');
headers_cleaned[prop_cleaned] = api_cfg['headers'][prop];
let value = merged_headers[prop];
if (value === null || value === undefined) continue;
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
headers_cleaned[prop_cleaned] = value;
}
if (log_lvl > 1) {
console.log('Cleaned Headers:', headers_cleaned);
// Auto-inject Authorization header if JWT is present but header is missing
const jwt = headers_cleaned['jwt'] || headers_cleaned['JWT'] || api_cfg['jwt'];
if (jwt && !headers_cleaned['Authorization'] && !headers_cleaned['authorization']) {
headers_cleaned['Authorization'] = `Bearer ${jwt}`;
}
const fetchOptions: RequestInit = {
method: 'DELETE',
headers: {
...headers_cleaned,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
headers_cleaned['Content-Type'] = 'application/json';
if (log_lvl > 1) {
console.log('Fetch Options:', fetchOptions);
console.log('Final cleaned headers:', headers_cleaned);
}
let fetch_method: any = fetch;
if (api_cfg.fetch) {
if (log_lvl > 1) {
console.log('Using custom fetch function from api_cfg!!!');
}
fetch_method = api_cfg.fetch;
}
for (let attempt = 1; attempt <= retry_count; attempt++) {
try {
const response = await fetch(url.toString(), fetchOptions);
const controller = new AbortController();
const timeoutId = setTimeout(() => {
console.error(`API DELETE request timed out after ${timeout}ms.`);
controller.abort();
}, timeout);
const fetchOptions: RequestInit = {
method: 'DELETE',
headers: headers_cleaned,
body: Object.keys(data).length > 0 ? JSON.stringify(data) : undefined,
signal: controller.signal
};
const response = await fetch_method(url.toString(), fetchOptions).catch(function (
error: any
) {
console.log(
'API DELETE Object *fetch* request was aborted or failed in an unexpected way.',
error
);
});
clearTimeout(timeoutId);
if (!response) {
throw new Error(
`HTTP fetch request was aborted or failed in an unexpected way! URL = ${url.toString()}`
);
}
if (log_lvl) {
console.log(`Response: status=${response.status} attempt=${attempt}`);
@@ -70,9 +127,17 @@ export const delete_object = async function delete_object({
if (!response.ok) {
if (response.status === 404) {
console.warn('404 Not Found. Returning null.');
return null; // Returning null since there were no results
return null;
}
throw new Error(`HTTP error! status: ${response.status}`);
const errorBody = await response.text();
console.error(`HTTP error! status: ${response.status}`, errorBody);
if (response.status >= 400 && response.status < 404) {
return false;
}
throw new Error(`HTTP error! status: ${response.status} - ${errorBody}`);
}
const json = await response.json();
@@ -82,49 +147,19 @@ export const delete_object = async function delete_object({
}
// Return the response data or metadata
return return_meta ? json : json.data;
// Robustly handle V3 response envelopes
return return_meta ? json : (json.data !== undefined ? json.data : json);
} 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: any) {
// 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

@@ -1,7 +1,11 @@
import type { key_val } from '$lib/stores/ae_stores';
import { get_object } from './api_get_object';
// Updated 2023-12-01
/**
* Fetches a single Aether object by its ID using the CRUD endpoint.
* Refactored 2026-01-08 to properly handle unauthenticated lookups (Bootstrap Paradox)
* and ensure clean header passing to get_object without mutating the global config.
*/
export async function get_ae_obj_id_crud({
api_cfg,
no_account_id = false,
@@ -15,11 +19,9 @@ export async function get_ae_obj_id_crud({
limit = 999999,
offset = 0,
data = {},
// key,
// jwt = null,
headers = {},
params = {},
timeout = 25000,
timeout = 60000,
return_meta = false,
log_lvl = 0
}: {
@@ -35,8 +37,6 @@ export async function get_ae_obj_id_crud({
limit?: number;
offset?: number;
data?: any;
// key: string,
// jwt?: string,
headers?: any;
params?: key_val;
timeout?: number;
@@ -44,129 +44,88 @@ export async function get_ae_obj_id_crud({
log_lvl?: number;
}) {
if (log_lvl) {
console.log('*** get_ae_obj_id_crud() ***');
console.log(`*** get_ae_obj_id_crud() *** Type: ${obj_type} ID: ${obj_id}`);
}
// data = {};
// data['super_key'] = key;
// data['jwt'] = jwt;
// NOTE: The key and or JWT should be in the header of the DELETE, GET, PATCH, POST
let endpoint = '';
if (obj_type == 'account') {
endpoint = `/crud/account/${obj_id}`;
} else if (obj_type == 'address') {
endpoint = `/crud/address/${obj_id}`;
} else if (obj_type == 'archive') {
endpoint = `/crud/archive/${obj_id}`;
} else if (obj_type == 'archive_content') {
endpoint = `/crud/archive/content/${obj_id}`;
} else if (obj_type == 'contact') {
endpoint = `/crud/contact/${obj_id}`;
} else if (obj_type == 'data_store') {
endpoint = `/crud/data_store/${obj_id}`;
} else if (obj_type == 'event') {
endpoint = `/crud/event/${obj_id}`;
} else if (obj_type == 'event_abstract') {
endpoint = `/crud/event/abstract/${obj_id}`;
} else if (obj_type == 'event_badge') {
endpoint = `/crud/event/badge/${obj_id}`;
} else if (obj_type == 'event_device') {
endpoint = `/crud/event/device/${obj_id}`;
} else if (obj_type == 'event_exhibit') {
endpoint = `/crud/event/exhibit/${obj_id}`;
} else if (obj_type == 'event_exhibit_tracking') {
endpoint = `/crud/event/exhibit/tracking/${obj_id}`;
} else if (obj_type == 'event_file') {
endpoint = `/crud/event/file/${obj_id}`;
} else if (obj_type == 'event_location') {
endpoint = `/crud/event/location/${obj_id}`;
} else if (obj_type == 'event_person') {
endpoint = `/crud/event/person/${obj_id}`;
} else if (obj_type == 'event_presentation') {
endpoint = `/crud/event/presentation/${obj_id}`;
} else if (obj_type == 'event_presenter') {
endpoint = `/crud/event/presenter/${obj_id}`;
} else if (obj_type == 'event_session') {
endpoint = `/crud/event/session/${obj_id}`;
} else if (obj_type == 'event_track') {
endpoint = `/crud/event/track/${obj_id}`;
} else if (obj_type == 'grant') {
endpoint = `/crud/grant/${obj_id}`;
} else if (obj_type == 'hosted_file') {
endpoint = `/crud/hosted_file/${obj_id}`;
} else if (obj_type == 'journal') {
endpoint = `/crud/journal/${obj_id}`;
} else if (obj_type == 'journal_entry') {
endpoint = `/crud/journal/entry/${obj_id}`;
} else if (obj_type == 'order') {
endpoint = `/crud/order/${obj_id}`;
} else if (obj_type == 'order_line') {
endpoint = `/crud/order/line/${obj_id}`;
} else if (obj_type == 'page') {
endpoint = `/crud/page/${obj_id}`;
} else if (obj_type == 'person') {
endpoint = `/crud/person/${obj_id}`;
} else if (obj_type == 'post') {
endpoint = `/crud/post/${obj_id}`;
} else if (obj_type == 'post_comment') {
endpoint = `/crud/post/comment/${obj_id}`;
} else if (obj_type == 'site') {
endpoint = `/crud/site/${obj_id}`;
} else if (obj_type == 'site_domain') {
endpoint = `/crud/site/domain/${obj_id}`;
} else if (obj_type == 'sponsorship_cfg') {
endpoint = `/crud/sponsorship/cfg/${obj_id}`;
} else if (obj_type == 'sponsorship') {
endpoint = `/crud/sponsorship/${obj_id}`;
// } else if (obj_type == 'user') {
// endpoint = `/crud/user/${obj_id}`;
// Map object types to their respective CRUD endpoints
const objTypeToEndpointMap: Record<string, string> = {
'account': '/crud/account',
'address': '/crud/address',
'archive': '/crud/archive',
'archive_content': '/crud/archive/content',
'contact': '/crud/contact',
'data_store': '/crud/data_store',
'event': '/crud/event',
'event_abstract': '/crud/event/abstract',
'event_badge': '/crud/event/badge',
'event_device': '/crud/event/device',
'event_exhibit': '/crud/event/exhibit',
'event_exhibit_tracking': '/crud/event/exhibit/tracking',
'event_file': '/crud/event/file',
'event_location': '/crud/event/location',
'event_person': '/crud/event/person',
'event_presentation': '/crud/event/presentation',
'event_presenter': '/crud/event/presenter',
'event_session': '/crud/event/session',
'event_track': '/crud/event/track',
'grant': '/crud/grant',
'hosted_file': '/crud/hosted_file',
'journal': '/crud/journal',
'journal_entry': '/crud/journal/entry',
'order': '/crud/order',
'order_line': '/crud/order/line',
'page': '/crud/page',
'person': '/crud/person',
'post': '/crud/post',
'post_comment': '/crud/post/comment',
'site': '/crud/site',
'site_domain': '/crud/site/domain',
'sponsorship_cfg': '/crud/sponsorship/cfg',
'sponsorship': '/crud/sponsorship'
};
if (objTypeToEndpointMap[obj_type]) {
endpoint = `${objTypeToEndpointMap[obj_type]}/${obj_id}`;
} else {
console.log(`Unknown object type: ${obj_type}`);
console.error(`Unknown object type: ${obj_type}`);
return false;
}
if (log_lvl) {
if (log_lvl > 1) {
console.log('Endpoint:', endpoint);
}
params['use_alt_table'] = use_alt_table;
params['use_alt_base'] = use_alt_base;
const final_params = {
...params,
use_alt_table: use_alt_table,
use_alt_base: use_alt_base
};
if (log_lvl) {
console.log('Params:', params);
}
const final_headers = { ...headers };
if (no_account_id) {
headers['x-no-account-id'] = 'Nothing to See Here';
delete headers['x-account-id'];
delete api_cfg['headers']['x-account-id'];
// headers['x-account-id'] = null;
// headers['x-account-id'] = '_XY7DXtc9Mxx';
// params['x_no_account_id_token'] = 'Nothing to See Here';
// Remove the x-account-id header
// if (headers['x-account-id']) {
// delete headers['x-account-id'];
// }
// headers['x-account-id'] = null;
// headers['x-no-account-id-token'] = 'Nothing to See Here'; // get_object() will fix the underscores to dashes
// This instructs get_object to skip account-id requirements
final_headers['x-no-account-id'] = 'Nothing to See Here';
final_headers['x-account-id'] = null; // Explicitly null to trigger removal in get_object
}
const object_obj_get_promise = await get_object({
const result = await get_object({
api_cfg: api_cfg,
endpoint: endpoint,
headers: headers,
params: params,
headers: final_headers,
params: final_params,
timeout: timeout,
log_lvl: log_lvl
log_lvl: log_lvl,
return_meta: return_meta
}).catch(function (error: any) {
console.log('API GET CRUD object ID request failed.', error);
console.error(`API GET CRUD object ID request failed for ${obj_type}/${obj_id}`, error);
return false;
});
if (log_lvl > 1) {
console.log('GET Object result =', object_obj_get_promise);
console.log('GET Object result =', result);
}
return object_obj_get_promise;
}
return result;
}

View File

@@ -57,18 +57,18 @@ export const get_object = async function get_object({
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
// Remove a header parameter if it is set to null
if (
api_cfg['headers'].hasOwnProperty('x-no-account-id') &&
api_cfg['headers']['x-no-account-id'] === null
) {
delete api_cfg['headers']['x-no-account-id'];
}
// Clean and merge headers
// Clean and merge headers without mutating the original api_cfg
const headers_cleaned: key_val = {};
const merged_headers = { ...api_cfg['headers'], ...headers };
// Handle "Bootstrap Paradox" for unauthenticated requests
if (merged_headers.hasOwnProperty('x-no-account-id')) {
delete merged_headers['x-account-id'];
if (merged_headers['x-no-account-id'] === null) {
merged_headers['x-no-account-id'] = 'Nothing to See Here';
}
}
// Standardize all headers to kebab-case and ensure string values
for (const prop in merged_headers) {
const prop_cleaned = prop.replaceAll('_', '-');

View File

@@ -1,19 +1,27 @@
// import axios from 'axios';
import type { key_val } from '$lib/stores/ae_stores';
// Updated 2024-05-23
/**
* Performs a PATCH request to the Aether API.
* Refactored 2026-01-08 to use standard fetch with timeout, custom fetch injection,
* standardized kebab-case headers, and robust V3 response handling.
*/
export const patch_object = async function patch_object({
api_cfg = null,
endpoint = '',
headers = {},
params = {},
data = {},
timeout = 60000,
return_meta = false,
log_lvl = 0,
retry_count = 5 // Number of retry attempts
retry_count = 5
}: {
api_cfg: any;
endpoint: string;
headers?: any;
params?: any;
data?: any;
timeout?: number;
return_meta?: boolean;
log_lvl?: number;
retry_count?: number;
@@ -23,6 +31,7 @@ export const patch_object = async function patch_object({
console.log('Params:', params);
if (log_lvl > 1) {
console.log('Data:', data);
console.log(`Base URL: ${api_cfg?.['base_url']}`);
}
}
@@ -33,35 +42,83 @@ export const patch_object = async function patch_object({
// 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]));
if (params) {
Object.keys(params).forEach((key) => url.searchParams.append(key, params[key]));
}
// Clean the headers
const headers_cleaned: Record<string, string> = {};
for (const prop in api_cfg['headers']) {
// Clean and merge headers without mutating the original api_cfg
const headers_cleaned: key_val = {};
const merged_headers = { ...api_cfg['headers'], ...headers };
// Handle "Bootstrap Paradox" for unauthenticated requests
if (merged_headers.hasOwnProperty('x-no-account-id')) {
delete merged_headers['x-account-id'];
if (merged_headers['x-no-account-id'] === null) {
merged_headers['x-no-account-id'] = 'Nothing to See Here';
}
}
for (const prop in merged_headers) {
const prop_cleaned = prop.replaceAll('_', '-');
headers_cleaned[prop_cleaned] = api_cfg['headers'][prop];
let value = merged_headers[prop];
if (value === null || value === undefined) continue;
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
headers_cleaned[prop_cleaned] = value;
}
if (log_lvl > 1) {
console.log('Cleaned Headers:', headers_cleaned);
// Auto-inject Authorization header if JWT is present but header is missing
const jwt = headers_cleaned['jwt'] || headers_cleaned['JWT'] || api_cfg['jwt'];
if (jwt && !headers_cleaned['Authorization'] && !headers_cleaned['authorization']) {
headers_cleaned['Authorization'] = `Bearer ${jwt}`;
}
const fetchOptions: RequestInit = {
method: 'PATCH',
headers: {
...headers_cleaned,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
headers_cleaned['Content-Type'] = 'application/json';
if (log_lvl > 1) {
console.log('Fetch Options:', fetchOptions);
console.log('Final cleaned headers:', headers_cleaned);
}
let fetch_method: any = fetch;
if (api_cfg.fetch) {
if (log_lvl > 1) {
console.log('Using custom fetch function from api_cfg!!!');
}
fetch_method = api_cfg.fetch;
}
for (let attempt = 1; attempt <= retry_count; attempt++) {
try {
const response = await fetch(url.toString(), fetchOptions);
const controller = new AbortController();
const timeoutId = setTimeout(() => {
console.error(`API PATCH request timed out after ${timeout}ms.`);
controller.abort();
}, timeout);
const fetchOptions: RequestInit = {
method: 'PATCH',
headers: headers_cleaned,
body: JSON.stringify(data),
signal: controller.signal
};
const response = await fetch_method(url.toString(), fetchOptions).catch(function (
error: any
) {
console.log(
'API PATCH Object *fetch* request was aborted or failed in an unexpected way.',
error
);
});
clearTimeout(timeoutId);
if (!response) {
throw new Error(
`HTTP fetch request was aborted or failed in an unexpected way! URL = ${url.toString()}`
);
}
if (log_lvl) {
console.log(`Response: status=${response.status} attempt=${attempt}`);
@@ -70,9 +127,17 @@ export const patch_object = async function patch_object({
if (!response.ok) {
if (response.status === 404) {
console.warn('404 Not Found. Returning null.');
return null; // Returning null since there were no results
return null;
}
throw new Error(`HTTP error! status: ${response.status}`);
const errorBody = await response.text();
console.error(`HTTP error! status: ${response.status}`, errorBody);
if (response.status >= 400 && response.status < 404) {
return false;
}
throw new Error(`HTTP error! status: ${response.status} - ${errorBody}`);
}
const json = await response.json();
@@ -82,63 +147,19 @@ export const patch_object = async function patch_object({
}
// Return the response data or metadata
return return_meta ? json : json.data;
// Robustly handle V3 response envelopes
return return_meta ? json : (json.data !== undefined ? json.data : json);
} catch (error) {
console.error(`API PATCH 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})`);
}
}
}
// 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;
};

View File

@@ -1,11 +1,11 @@
// import axios from 'axios';
import type { key_val } from '$lib/stores/ae_stores';
export const temp_post_blob_percent_completed = 0;
export const post_blob_percent_completed = temp_post_blob_percent_completed;
export const temp_post_object_percent_completed = 0;
export const post_object_percent_completed = temp_post_object_percent_completed;
// Updated 2026-01-07
// Updated 2026-01-08
export const post_object = async function post_object({
api_cfg = null,
endpoint = '',
@@ -13,6 +13,7 @@ export const post_object = async function post_object({
params = {},
data = {},
form_data = null,
timeout = 60000,
return_meta = false,
return_blob = false,
filename = '',
@@ -28,6 +29,7 @@ export const post_object = async function post_object({
params?: any;
data?: any;
form_data?: any;
timeout?: number;
return_meta?: boolean;
return_blob?: boolean;
filename?: string;
@@ -53,27 +55,29 @@ export const post_object = async function post_object({
}
}
// console.log('HERE!! API POST 0');
if (!api_cfg) {
console.error('No API Config was provided. Returning false.');
return false;
}
// console.log('HERE!! API POST 1');
// Construct the URL with query parameters
const url = new URL(endpoint, api_cfg['base_url']);
if (params) {
Object.keys(params).forEach((key) => url.searchParams.append(key, params[key]));
}
// console.log('HERE!! API POST 2');
// Clean and merge headers
const headers_cleaned: Record<string, string> = {};
const headers_cleaned: key_val = {};
const merged_headers = { ...api_cfg['headers'], ...headers };
// Handle "Bootstrap Paradox" for unauthenticated requests
if (merged_headers.hasOwnProperty('x-no-account-id')) {
delete merged_headers['x-account-id'];
if (merged_headers['x-no-account-id'] === null) {
merged_headers['x-no-account-id'] = 'Nothing to See Here';
}
}
for (const prop in merged_headers) {
const prop_cleaned = prop.replaceAll('_', '-');
let value = merged_headers[prop];
@@ -92,10 +96,9 @@ export const post_object = async function post_object({
}
if (form_data) {
// headers_cleaned['Content-Type'] = 'multipart/form-data';
delete headers_cleaned['content-type'];
delete headers_cleaned['Content-Type'];
console.log('Form Data:', form_data);
if (log_lvl > 1) console.log('Form Data:', form_data);
} else {
headers_cleaned['Content-Type'] = 'application/json';
}
@@ -104,15 +107,21 @@ export const post_object = async function post_object({
console.log('Final cleaned headers:', headers_cleaned);
}
// console.log('HERE!! API POST 4');
let fetch_method: any = fetch;
if (api_cfg.fetch) {
if (log_lvl > 1) {
console.log('Using custom fetch function from api_cfg!!!');
}
fetch_method = api_cfg.fetch;
}
for (let attempt = 1; attempt <= retry_count; attempt++) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => {
console.error('API POST request timed out.');
console.error(`API POST request timed out after ${timeout}ms.`);
controller.abort();
}, 20000); // 20-second timeout
}, timeout);
const fetchOptions: RequestInit = {
method: 'POST',
@@ -121,14 +130,25 @@ export const post_object = async function post_object({
signal: controller.signal
};
console.log('Final fetch options for post_object:', fetchOptions);
if (log_lvl > 1) {
console.log('Fetch Options:', fetchOptions);
}
const response = await fetch(url.toString(), fetchOptions);
clearTimeout(timeoutId); // Clear the timeout if the request completes in time
const response = await fetch_method(url.toString(), fetchOptions).catch(function (
error: any
) {
console.log(
'API POST Object *fetch* request was aborted or failed in an unexpected way.',
error
);
});
clearTimeout(timeoutId);
if (!response) {
throw new Error(
`HTTP fetch request was aborted or failed in an unexpected way! URL = ${url.toString()}`
);
}
if (log_lvl) {
console.log(`Response: status=${response.status} attempt=${attempt}`);
@@ -137,7 +157,7 @@ export const post_object = async function post_object({
if (!response.ok) {
if (response.status === 404) {
console.warn('404 Not Found. Returning null.');
return null; // Returning null since there were no results
return null;
}
const errorBody = await response.text();
@@ -181,7 +201,8 @@ export const post_object = async function post_object({
}
// Return the response data or metadata
return return_meta ? json : json.data;
// Robustly handle V3 response envelopes
return return_meta ? json : (json.data !== undefined ? json.data : json);
} else {
const blob = await response.blob();
@@ -201,183 +222,14 @@ export const post_object = async function post_object({
} catch (error) {
console.error(`API POST 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})`);
}
}
}
// let axios_api = axios.create({
// baseURL: api_cfg['base_url'],
// /* other custom settings */
// });
// axios_api.defaults.headers = api_cfg['headers'];
// console.log('Axios API', axios_api);
// // console.log('Axios API POST', axios_api.post);
// // if (typeof data == 'FormData') {
// if (form_data) {
// axios_api.defaults.headers['content-type'] = 'multipart/form-data';
// data = form_data;
// } else {
// axios_api.defaults.headers['content-type'] = 'application/json';
// }
// if (!return_blob) {
// let response_data = await axios_api.post(
// endpoint,
// data,
// {
// params: params,
// onUploadProgress: (progressEvent) => {
// let percent_completed = Math.round(
// (progressEvent.loaded * 100) / progressEvent.total
// );
// console.log('POST Progress:', progressEvent.progress, 'Total:', progressEvent.total, 'Loaded:', progressEvent.loaded, 'Percent Completed', percent_completed);
// temp_post_object_percent_completed = percent_completed;
// try {
// window.postMessage({
// type: 'api_post_json_form',
// status: 'uploading',
// task_id: task_id,
// endpoint: endpoint,
// size_total: progressEvent.total,
// size_loaded: progressEvent.loaded,
// percent_completed: percent_completed,
// progress: progressEvent.progress,
// rate: progressEvent.rate,
// },
// '*'
// );
// } catch (error) {
// console.log('Error posting message to window:', error);
// }
// }
// }
// )
// .then(function (response) {
// console.log('POST Response Data:', response.data);
// try {
// window.postMessage({
// type: 'api_post_json_form',
// status: 'complete',
// task_id: task_id,
// endpoint: endpoint,
// size_total: 0,
// size_loaded: 0,
// percent_completed: 100,
// progress: 100,
// rate: 0,
// },
// '*'
// );
// } catch (error) {
// console.log('Error posting message to window:', error);
// }
// if (response.data['data'].result === null) {
// // This should mean that the request was successful, but a result of None/null was returned from Aether API.
// // console.log('Returning null after POST');
// return null;
// } else {
// // This should mean that the request was successful, and a result with data was returned from Aether API.
// // console.log('Returning data after POST');
// return response.data['data'];
// }
// //return response.data;
// })
// .catch(function (error: any) {
// 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:', response_data);
// }
// axios_api.defaults.headers['content-type'] = 'application/json';
// return response_data;
// } else {
// // console.log('Expecting a Blob to be returned...');
// let response_data_promise = await axios_api.post(
// endpoint,
// data,
// {
// params: params,
// responseType: 'blob',
// onDownloadProgress: (progressEvent) => {
// let percent_completed = Math.round(
// (progressEvent.loaded * 100) / progressEvent.total
// );
// console.log('POST Blob Progress:', progressEvent.progress, 'Total:', progressEvent.total, 'Loaded:', progressEvent.loaded, 'Percent Completed', percent_completed);
// temp_post_blob_percent_completed = percent_completed;
// }
// }
// )
// .then(function (response) {
// if (log_lvl) {
// console.log(response);
// }
// const { data, headers } = response
// console.log(headers);
// if (filename) {
// } else if (headers['content-disposition']) {
// filename = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1');
// } else {
// filename = 'unknown_file.ext';
// }
// if (auto_download) {
// const url = window.URL.createObjectURL(new Blob([response.data]));
// const link = document.createElement('a');
// link.href = url;
// // link.setAttribute('download', 'event_exhibit_tracking_export.xlsx'); //or any other extension
// link.setAttribute('download', filename); //or any other extension
// document.body.appendChild(link);
// link.click();
// return true;
// } else {
// return response;
// }
// });
// if (response_data_promise) {
// // The most common and expected response.
// // console.log('Returning result. This is generally expected.');
// // let test_blob = new Blob([response_data_promise.data]);
// // console.log(test_blob);
// // return test_blob;
// // console.log(response_data_promise.blob());
// return response_data_promise;
// } else {
// // This generally should not happen. It likely means the query was bad or an API issue.
// console.log('Returning unknown. This should not happen in most cases.');
// Promise.reject(new Error('fail')).then(resolved, rejected);
// }
// }
};
// function resolved(result: any) {
// console.log('Resolved');
// }
// function rejected(result: any) {
// console.error(result);
// }