Add data_visualization/js/api.js
This commit is contained in:
parent
eb89a6d7b9
commit
70c4fce324
1 changed files with 44 additions and 0 deletions
44
data_visualization/js/api.js
Normal file
44
data_visualization/js/api.js
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
/**
|
||||||
|
* @module api
|
||||||
|
* Kommuniziert mit der Backend-Route /data und liefert Messdaten.
|
||||||
|
* @description Dieses Modul stellt Funktionen zum Abrufen der Sensordaten bereit.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Holt Sensorwerte (Temperatur, Luftfeuchtigkeit, Licht) von der API.
|
||||||
|
* @async
|
||||||
|
* @function fetchSensorData
|
||||||
|
* @returns {Promise<Array<{timestamp: string, location_id: string, temperature: number, humidity: number, light: number}>>} Messdaten-Array
|
||||||
|
* @throws {Error} Wenn der Abruf fehlschlägt oder die Antwort ungültig ist.
|
||||||
|
*/
|
||||||
|
export async function fetchSensorData() {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/data', {
|
||||||
|
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: expected an array.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return data.map(item => ({
|
||||||
|
timestamp: item.timestamp ?? '',
|
||||||
|
location_id: item.location_id ?? '',
|
||||||
|
temperature: typeof item.temperature === 'number' ? item.temperature : null,
|
||||||
|
humidity: typeof item.humidity === 'number' ? item.humidity : null,
|
||||||
|
light: typeof item.light === 'number' ? item.light : null
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Fehler beim Abrufen der Sensordaten:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue