getExternalWeather.js 900 B

12345678910111213141516171819202122232425262728293031
  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. // Fetch data from external API
  7. try {
  8. const res = await axios.get(
  9. `http://api.weatherapi.com/v1/current.json?key=${secret}&q=${lat},${long}`
  10. );
  11. // Save weather data
  12. const cursor = res.data.current;
  13. const weatherData = await Weather.create({
  14. externalLastUpdate: cursor.last_updated,
  15. tempC: cursor.temp_c,
  16. tempF: cursor.temp_f,
  17. isDay: cursor.is_day,
  18. cloud: cursor.cloud,
  19. conditionText: cursor.condition.text,
  20. conditionCode: cursor.condition.code,
  21. });
  22. return weatherData;
  23. } catch (err) {
  24. throw new Error('External API request failed');
  25. }
  26. };
  27. module.exports = getExternalWeather;