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 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;
};