2021-05-17 19:23:54 +03:00
|
|
|
const Weather = require('../models/Weather');
|
|
|
|
const axios = require('axios');
|
2021-10-22 01:42:27 +03:00
|
|
|
const loadConfig = require('./loadConfig');
|
2021-05-17 19:23:54 +03:00
|
|
|
|
|
|
|
const getExternalWeather = async () => {
|
2021-10-22 01:42:27 +03:00
|
|
|
const { WEATHER_API_KEY: secret, lat, long } = await loadConfig();
|
2021-05-17 19:23:54 +03:00
|
|
|
|
|
|
|
// Fetch data from external API
|
|
|
|
try {
|
2021-10-22 01:42:27 +03:00
|
|
|
const res = await axios.get(
|
|
|
|
`http://api.weatherapi.com/v1/current.json?key=${secret}&q=${lat},${long}`
|
|
|
|
);
|
2021-05-17 19:23:54 +03:00
|
|
|
|
|
|
|
// Save weather data
|
|
|
|
const cursor = res.data.current;
|
2021-06-01 15:54:47 +03:00
|
|
|
const weatherData = await Weather.create({
|
2021-05-17 19:23:54 +03:00
|
|
|
externalLastUpdate: cursor.last_updated,
|
|
|
|
tempC: cursor.temp_c,
|
|
|
|
tempF: cursor.temp_f,
|
|
|
|
isDay: cursor.is_day,
|
2021-06-07 13:17:10 +03:00
|
|
|
cloud: cursor.cloud,
|
2021-05-17 19:23:54 +03:00
|
|
|
conditionText: cursor.condition.text,
|
2021-10-22 01:42:27 +03:00
|
|
|
conditionCode: cursor.condition.code,
|
2021-05-17 19:23:54 +03:00
|
|
|
});
|
2021-06-01 15:54:47 +03:00
|
|
|
return weatherData;
|
2021-05-17 19:23:54 +03:00
|
|
|
} catch (err) {
|
2021-06-01 15:54:47 +03:00
|
|
|
throw new Error('External API request failed');
|
2021-05-17 19:23:54 +03:00
|
|
|
}
|
2021-10-22 01:42:27 +03:00
|
|
|
};
|
2021-05-17 19:23:54 +03:00
|
|
|
|
2021-10-22 01:42:27 +03:00
|
|
|
module.exports = getExternalWeather;
|