getExternalWeather.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  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. //units = standard, metric, imperial
  7. // Fetch data from external API
  8. try {
  9. const res = await axios.get(
  10. `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${secret}&units=metric`
  11. );
  12. // Save weather data
  13. const cursor = res.data;
  14. const isDay = (Math.floor(Date.now()/1000) < cursor.sys.sunset) | 0
  15. const weatherData = await Weather.create({
  16. externalLastUpdate: cursor.dt,
  17. tempC: cursor.main.temp,
  18. tempF: 0,
  19. isDay: isDay,
  20. cloud: cursor.clouds.all,
  21. conditionText: cursor.weather[0].main,
  22. conditionCode: cursor.weather[0].id,
  23. humidity: cursor.main.humidity,
  24. windK: cursor.wind.speed,
  25. windM: 0,
  26. });
  27. return weatherData;
  28. } catch (err) {
  29. throw new Error('External API request failed');
  30. }
  31. };
  32. module.exports = getExternalWeather;