jubilee-server/server/weather.js
Martin Donnelly 84365f816d init
2021-11-29 15:14:46 +00:00

119 lines
3.1 KiB
JavaScript

const Client = require('request-json');
const logger = require('log4js').getLogger('Weather');
const weather = require('openweather-apis');
const { reduceWeather } = require('./reducers/weather');
const request = require('request');
logger.level = 'debug';
logger.label = 'Weather';
const openWeatherApiKey = process.env.openweatherAPI || '936a0ed9eb23b95cf08fc9f693c24264';
const darkskyApiKey = process.env.darkskyApiKey || '9ad2a41d420f3cf4960571bb886f710c';
const dsURL = `https://api.darksky.net/forecast/${ darkskyApiKey }/`;
const DSclient = Client.createClient(`https://api.darksky.net/forecast/${ darkskyApiKey }/`);
weather.setAPPID(openWeatherApiKey);
weather.setLang('en');
// weather.setCity('Glasgow City');
function doGetOpenWeather(ll) {
const [lat, long ] = ll.split(',');
return new Promise((resolve, reject) => {
weather.setCoordinate(lat, long);
weather.getWeatherForecast( function(err, wData) {
if (err)
return reject(err);
else
return resolve(wData);
});
});
}
function doGetOpenWeatherForecast(ll) {
const [lat, long ] = ll.split(',');
return new Promise((resolve, reject) => {
weather.setCoordinate(lat, long);
weather.getWeatherForecastForDays(5, function(err, wData) {
if (err)
return reject(err);
else
return resolve(wData);
});
});
}
function doGetDarkSkyWeather(ll) {
const query = `${ll}?units=uk2&exclude=daily,flags,minutely,hourly`;
logger.debug(`https://api.darksky.net/forecast/${ darkskyApiKey }/${query}`);
return new Promise((resolve, reject) => {
DSclient.get(query, function(err, res, body) {
if (err || !body || !body.currently)
return reject(err);
return resolve(body);
});
});
}
function doGetFullForcast(ll) {
const query = `${ll}?units=uk2&exclude=flags,minutely`;
logger.debug('doGetFullForcast');
logger.debug(query);
return new Promise((resolve, reject) => {
DSclient.get(query, function(err, res, body) {
if (err || !body || !body.currently)
return reject(err);
const output = reduceWeather(body);
return resolve(output);
});
});
}
function doGetFullForcastV2(ll) {
const query = `${ll}?units=uk2&exclude=flags,minutely`;
logger.debug('doGetFullForcastV2');
const url = `${dsURL}${query}`;
logger.debug(url);
return new Promise(function(resolve, reject) {
request.get({ 'url':url }, function(err, resp, body) {
if (err) {
logger.error(err);
return reject(err);
}
// Logger.error(err);
// return reject(err);
// Throw err;
console.log;
const output = reduceWeather(body);
output.fullBody = JSON.parse(body);
output.timestamp = new Date().getTime();
console.log(output);
return resolve(output);
}, function(error, response, body) {
console.log(response);
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
return reject(error);
}
});
});
}
module.exports = { doGetOpenWeather, doGetOpenWeatherForecast, doGetDarkSkyWeather, doGetFullForcast, doGetFullForcastV2 };