diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js index 9e1710f..3f49296 100755 --- a/frontend/src/lib/api.js +++ b/frontend/src/lib/api.js @@ -54,37 +54,48 @@ async function postApi(endpoint, body) { } // [/DEF:postApi] +// [DEF:requestApi:Function] +// @PURPOSE: Generic request wrapper. +async function requestApi(endpoint, method = 'GET', body = null) { + try { + console.log(`[api.requestApi][Action] ${method} to context={{'endpoint': '${endpoint}'}}`); + const options = { + method, + headers: { + 'Content-Type': 'application/json', + }, + }; + if (body) { + options.body = JSON.stringify(body); + } + const response = await fetch(`${API_BASE_URL}${endpoint}`, options); + if (!response.ok) { + const errorData = await response.json().catch(() => ({})); + throw new Error(errorData.detail || `API request failed with status ${response.status}`); + } + return await response.json(); + } catch (error) { + console.error(`[api.requestApi][Coherence:Failed] Error ${method} to ${endpoint}:`, error); + addToast(error.message, 'error'); + throw error; + } +} + // [DEF:api:Data] // @PURPOSE: API client object with specific methods. export const api = { getPlugins: () => fetchApi('/plugins/'), getTasks: () => fetchApi('/tasks/'), getTask: (taskId) => fetchApi(`/tasks/${taskId}`), - createTask: (pluginId, params) => postApi('/tasks', { plugin_id: pluginId, params }), + createTask: (pluginId, params) => postApi('/tasks/', { plugin_id: pluginId, params }), // Settings - getSettings: () => fetchApi('/settings'), - updateGlobalSettings: (settings) => { - return fetch(`${API_BASE_URL}/settings/global`, { - method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(settings) - }).then(res => res.json()); - }, + getSettings: () => fetchApi('/settings/'), + updateGlobalSettings: (settings) => requestApi('/settings/global', 'PATCH', settings), getEnvironments: () => fetchApi('/settings/environments'), addEnvironment: (env) => postApi('/settings/environments', env), - updateEnvironment: (id, env) => { - return fetch(`${API_BASE_URL}/settings/environments/${id}`, { - method: 'PUT', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(env) - }).then(res => res.json()); - }, - deleteEnvironment: (id) => { - return fetch(`${API_BASE_URL}/settings/environments/${id}`, { - method: 'DELETE' - }).then(res => res.json()); - }, + updateEnvironment: (id, env) => requestApi(`/settings/environments/${id}`, 'PUT', env), + deleteEnvironment: (id) => requestApi(`/settings/environments/${id}`, 'DELETE'), testEnvironmentConnection: (id) => postApi(`/settings/environments/${id}/test`, {}), }; // [/DEF:api_module]