getExternalWeather.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. const Weather = require('../models/Weather');
  2. const axios = require('axios');
  3. const loadConfig = require('./loadConfig');
  4. const getExternalWeather = async () => {
  5. const { WEATHER_API_KEY: secret, lat, long } = await loadConfig();
  6. if (!secret) {
  7. throw new Error('API key was not found. Weather updated failed');
  8. }
  9. if (!lat || !long) {
  10. throw new Error('Location was not found. Weather updated failed');
  11. }
  12. // Fetch data from external API
  13. try {
  14. const res = await axios.get(
  15. `http://api.weatherapi.com/v1/current.json?key=${secret}&q=${lat},${long}`
  16. );
  17. // Save weather data
  18. const cursor = res.data.current;
  19. const weatherData = await Weather.create({
  20. externalLastUpdate: cursor.last_updated,
  21. tempC: cursor.temp_c,
  22. tempF: cursor.temp_f,
  23. isDay: cursor.is_day,
  24. cloud: cursor.cloud,
  25. conditionText: cursor.condition.text,
  26. conditionCode: cursor.condition.code,
  27. });
  28. return weatherData;
  29. } catch (err) {
  30. throw new Error('External API request failed');
  31. }
  32. };
  33. module.exports = getExternalWeather;