diff --git a/index.js b/index.js index 9ad31ee..74b1a61 100644 --- a/index.js +++ b/index.js @@ -102,6 +102,10 @@ getData(buildPath(), callback); }; + weather.getWeatherForecast = function(callback){ + getData(buildPathForecast(), callback); + }; + weather.getWeatherForecastForDays = function(days, callback){ getData(buildPathForecastForDays(days), callback); }; @@ -169,20 +173,32 @@ return '/data/2.5/weather?' + getCoordinate() + '&units=' + config.units + '&lang=' + config.lan + '&mode=json&APPID=' + config.APPID; }; + function buildPathForecast(){ + return '/data/2.5/forecast?' + getCoordinate() + '&units=' + config.units + '&lang=' + config.lan + '&mode=json&APPID=' + config.APPID; + }; + function buildPathForecastForDays(days){ return '/data/2.5/forecast/daily?' + getCoordinate() + '&cnt=' + days + '&units=' + config.units + '&lang=' + config.lan + '&mode=json&APPID=' + config.APPID; }; - function getData(url, callback){ + function getData(url, callback, tries){ options.path = url; http.get(options, function(res){ + var chunks = ''; res.setEncoding('utf-8'); - res.on('data', function (chunk) { - + res.on('data', function(chunk) { + chunks += chunk; + }); + res.on('end', function () { var parsed = {}; + + if (!chunks && (!tries || tries < 3)) { + return getData(url, callback, (tries||0)+1); + } + // Try-Catch added by Mikael Aspehed try{ - parsed = JSON.parse(chunk) + parsed = JSON.parse(chunks) }catch(e){ parsed = {error:e} } diff --git a/test/weather.js b/test/weather.js index 07bfb59..1e2442c 100644 --- a/test/weather.js +++ b/test/weather.js @@ -78,6 +78,14 @@ describe('OpenWeatherMap ', function(){ done(); }); }); + it('Should present short-term weather forecast', function(done){ + weather.getWeatherForecast(function(err, obj){ + expect(obj).not.empty; + expect(obj.cnt).is.equal(40); + expect(obj.list).is.not.empty; + done(); + }); + }); it('Should present 3 day weather forecast', function(done){ weather.getWeatherForecastForDays(3, function(err, obj){ expect(obj).not.empty;