getExternalWeather.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const Config = require('../models/Config');
  2. const Weather = require('../models/Weather');
  3. const axios = require('axios');
  4. const getExternalWeather = async () => {
  5. // Get API key from database
  6. let secret = await Config.findOne({
  7. where: { key: 'WEATHER_API_KEY' }
  8. });
  9. if (!secret) {
  10. console.log('API key was not found');
  11. return;
  12. }
  13. secret = secret.value;
  14. // Fetch data from external API
  15. try {
  16. const res = await axios.get(`http://api.weatherapi.com/v1/current.json?key=${secret}&q=52.229676,21.012229`);
  17. // For dev
  18. // console.log(res.data);
  19. // Save weather data
  20. const cursor = res.data.current;
  21. await Weather.create({
  22. externalLastUpdate: cursor.last_updated,
  23. tempC: cursor.temp_c,
  24. tempF: cursor.temp_f,
  25. isDay: cursor.is_day,
  26. conditionText: cursor.condition.text,
  27. conditionCode: cursor.condition.code
  28. });
  29. } catch (err) {
  30. console.log(err);
  31. console.log('External API request failed');
  32. return;
  33. }
  34. }
  35. module.exports = getExternalWeather;