2021-05-17 19:23:54 +03:00
|
|
|
const Config = require('../models/Config');
|
|
|
|
const Weather = require('../models/Weather');
|
|
|
|
const axios = require('axios');
|
|
|
|
|
|
|
|
const getExternalWeather = async () => {
|
2021-05-19 19:26:57 +03:00
|
|
|
// Get config from database
|
|
|
|
const config = await Config.findAll();
|
|
|
|
|
|
|
|
// Find and check values
|
|
|
|
const secret = config.find(pair => pair.key === 'WEATHER_API_KEY');
|
|
|
|
const lat = config.find(pair => pair.key === 'lat');
|
|
|
|
const long = config.find(pair => pair.key === 'long');
|
2021-05-17 19:23:54 +03:00
|
|
|
|
|
|
|
if (!secret) {
|
2021-06-07 13:17:10 +03:00
|
|
|
throw new Error('API key was not found. Weather updated failed');
|
2021-05-17 19:23:54 +03:00
|
|
|
}
|
|
|
|
|
2021-05-19 19:26:57 +03:00
|
|
|
if (!lat || !long) {
|
2021-06-07 13:17:10 +03:00
|
|
|
throw new Error('Location was not found. Weather updated failed');
|
2021-05-19 19:26:57 +03:00
|
|
|
}
|
2021-05-17 19:23:54 +03:00
|
|
|
|
|
|
|
// Fetch data from external API
|
|
|
|
try {
|
2021-05-19 19:26:57 +03:00
|
|
|
const res = await axios.get(`http://api.weatherapi.com/v1/current.json?key=${secret.value}&q=${lat.value},${long.value}`);
|
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,
|
|
|
|
conditionCode: cursor.condition.code
|
|
|
|
});
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = getExternalWeather;
|