getExternalWeather.js 1.1 KB

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