1
0
Fork 0
mirror of https://github.com/pawelmalak/flame.git synced 2025-07-20 03:59:36 +02:00
flame/utils/getExternalWeather.js

43 lines
1.3 KiB
JavaScript
Raw Normal View History

const Weather = require('../models/Weather');
const axios = require('axios');
const loadConfig = require('./loadConfig');
const getExternalWeather = async () => {
2024-09-10 22:56:21 +02:00
const { lat, long, isCelsius } = await loadConfig();
const params = {
latitude: lat,
longitude: long,
current: ['is_day', 'temperature_2m', 'relative_humidity_2m', 'cloud_cover', 'wind_speed_10m', 'weathercode'],
};
if (!isCelsius) {
params.temperature_unit = "fahrenheit";
}
// Fetch data from external API
try {
2024-09-10 22:56:21 +02:00
const res = await axios.get('https://api.open-meteo.com/v1/forecast', { params });
// TODO weather code
// Save weather data
const cursor = res.data.current;
const weatherData = await Weather.create({
2024-09-10 22:56:21 +02:00
externalLastUpdate: cursor.time,
tempC: cursor.temperature_2m,
2024-09-10 22:27:29 +02:00
tempF: cursor.temperature_2m,
isDay: Boolean(cursor.is_day),
cloud: cursor.cloud_cover,
2024-09-10 22:56:21 +02:00
conditionText: '',
conditionCode: 1, // cursor.weathercode
2024-09-10 22:27:29 +02:00
humidity: cursor.relative_humidity_2m,
windK: cursor.wind_speed_10m,
windM: cursor.wind_speed_10m,
});
return weatherData;
} catch (err) {
2024-09-10 22:56:21 +02:00
// TODO to update
2024-09-10 22:27:29 +02:00
throw new Error(err);
//throw new Error('External API request failed');
}
};
module.exports = getExternalWeather;