2021-05-17 18:23:54 +02:00
|
|
|
const Weather = require('../models/Weather');
|
|
|
|
const axios = require('axios');
|
2021-10-22 00:42:27 +02:00
|
|
|
const loadConfig = require('./loadConfig');
|
2021-05-17 18:23:54 +02:00
|
|
|
|
|
|
|
const getExternalWeather = async () => {
|
2021-10-22 00:42:27 +02:00
|
|
|
const { WEATHER_API_KEY: secret, lat, long } = await loadConfig();
|
2021-05-17 18:23:54 +02:00
|
|
|
|
|
|
|
// Fetch data from external API
|
|
|
|
try {
|
2024-09-10 22:27:29 +02:00
|
|
|
const res = await axios.get('https://api.open-meteo.com/v1/forecast', { params: {
|
|
|
|
latitude: lat,
|
|
|
|
longitude: long,
|
|
|
|
current: ['is_day', 'temperature_2m', 'relative_humidity_2m', 'cloud_cover', 'wind_speed_10m', 'weathercode'],
|
|
|
|
} });
|
2021-05-17 18:23:54 +02:00
|
|
|
|
|
|
|
// Save weather data
|
|
|
|
const cursor = res.data.current;
|
2021-06-01 14:54:47 +02:00
|
|
|
const weatherData = await Weather.create({
|
2024-09-10 22:27:29 +02:00
|
|
|
externalLastUpdate: "externalLastUpdate",
|
|
|
|
tempC: cursor.temperature_2m, // can not be 0 put like minus kelvin
|
|
|
|
tempF: cursor.temperature_2m,
|
|
|
|
isDay: Boolean(cursor.is_day),
|
|
|
|
cloud: cursor.cloud_cover,
|
|
|
|
conditionText: "conditionText",
|
|
|
|
conditionCode: 1,
|
|
|
|
humidity: cursor.relative_humidity_2m,
|
|
|
|
windK: cursor.wind_speed_10m,
|
|
|
|
windM: cursor.wind_speed_10m,
|
2021-05-17 18:23:54 +02:00
|
|
|
});
|
2021-06-01 14:54:47 +02:00
|
|
|
return weatherData;
|
2021-05-17 18:23:54 +02:00
|
|
|
} catch (err) {
|
2024-09-10 22:27:29 +02:00
|
|
|
throw new Error(err);
|
|
|
|
//throw new Error('External API request failed');
|
2021-05-17 18:23:54 +02:00
|
|
|
}
|
2021-10-22 00:42:27 +02:00
|
|
|
};
|
2021-05-17 18:23:54 +02:00
|
|
|
|
2021-10-22 00:42:27 +02:00
|
|
|
module.exports = getExternalWeather;
|