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 () => {
|
2022-11-30 20:46:28 +00:00
|
|
|
const { WEATHER_API_KEY: secret, lat, long, isCelsius } = await loadConfig();
|
|
|
|
|
|
|
|
//units = standard, metric, imperial
|
|
|
|
const units = isCelsius?'metric':'imperial'
|
2021-05-17 18:23:54 +02:00
|
|
|
|
|
|
|
// Fetch data from external API
|
|
|
|
try {
|
2021-10-22 00:42:27 +02:00
|
|
|
const res = await axios.get(
|
2022-11-30 20:46:28 +00:00
|
|
|
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${secret}&units=${units}`
|
2021-10-22 00:42:27 +02:00
|
|
|
);
|
2021-05-17 18:23:54 +02:00
|
|
|
|
|
|
|
// Save weather data
|
2022-11-30 20:46:28 +00:00
|
|
|
const cursor = res.data;
|
|
|
|
const isDay = (Math.floor(Date.now()/1000) < cursor.sys.sunset) | 0
|
2021-06-01 14:54:47 +02:00
|
|
|
const weatherData = await Weather.create({
|
2022-11-30 20:46:28 +00:00
|
|
|
externalLastUpdate: cursor.dt,
|
|
|
|
tempC: cursor.main.temp,
|
|
|
|
tempF: cursor.main.temp,
|
|
|
|
isDay: isDay,
|
|
|
|
cloud: cursor.clouds.all,
|
|
|
|
conditionText: cursor.weather[0].main,
|
|
|
|
conditionCode: cursor.weather[0].id,
|
|
|
|
humidity: cursor.main.humidity,
|
|
|
|
windK: cursor.wind.speed,
|
|
|
|
windM: 0,
|
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) {
|
2021-06-01 14:54:47 +02:00
|
|
|
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;
|