44 lines
1.4 KiB
JavaScript
44 lines
1.4 KiB
JavaScript
/**
|
|
* @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;
|
|
}
|
|
}
|