diff --git a/drift_matrix_visualization/js/api.js b/drift_matrix_visualization/js/api.js new file mode 100644 index 0000000..d1d40d6 --- /dev/null +++ b/drift_matrix_visualization/js/api.js @@ -0,0 +1,48 @@ +/** + * @module api + * Data layer module for fetching Drift-Matrix data. + * + * Provides a function to retrieve matrix data from the backend. + */ + +/** + * Fetches Drift-Matrix data from the API for a given run. + * + * @async + * @function fetchMatrixData + * @param {string|number} run_id - The identifier of the run for which drift data should be retrieved. + * @returns {Promise>} - The matrix data as JSON array. + * @throws {Error} Throws if the fetch fails or response is invalid. + */ +export async function fetchMatrixData(run_id) { + if (!run_id) { + throw new Error('fetchMatrixData: Missing required parameter run_id'); + } + + const url = new URL('/drift-matrix', window.location.origin); + url.searchParams.append('run_id', run_id); + + try { + const response = await fetch(url.toString(), { + method: 'GET', + headers: { + 'Accept': 'application/json' + } + }); + + if (!response.ok) { + throw new Error(`API request failed with status ${response.status}`); + } + + const data = await response.json(); + + if (!Array.isArray(data)) { + throw new Error('Invalid API response format: expected an array'); + } + + return data; + } catch (error) { + console.error('Error fetching drift matrix data:', error); + throw error; + } +}