weather-underground-by-zip
Version:
simple weather underground call using zipcode
87 lines (64 loc) • 2.84 kB
JavaScript
;
require("core-js/modules/es.array.concat");
require("core-js/modules/es.array.join");
require("core-js/modules/es.array.slice");
require("core-js/modules/es.parse-float");
require("core-js/modules/es.parse-int");
require("core-js/modules/es.regexp.exec");
require("core-js/modules/es.string.match");
require("core-js/modules/es.string.split");
var superagent = require('superagent');
module.exports = function WeatherUnderground() {
var _this = this;
if (!(this instanceof WeatherUnderground)) {
return new WeatherUnderground();
}
this.grabTemperature = function (body) {
var tempRegex = /<\s*div[^>]*class="BNeawe iBp4i AP7Wnd">([^<].*?)<\s*\/\s*div>/;
var locationRegex = /<\s*span[^>]*class="BNeawe tAd8D AP7Wnd">(.*?)<\s*\/\s*span>/;
var infoRegex = /<\s*div[^>]*class="BNeawe tAd8D AP7Wnd">([^<][\S\s]*?)<\s*\/\s*div>/;
var temperaturePieces = body.match(tempRegex); // match looks like this "80�F"
if (temperaturePieces !== null) {
// checking for errors if the div wasn't matched
temperaturePieces = temperaturePieces[1].split('');
} else {
return 'There has been an error processing this zipcode (div was not matched in body)';
}
var temperatureUnit = temperaturePieces.pop();
temperaturePieces.pop(); // remove the degrees symbol
var temperature = parseFloat(temperaturePieces.join(''));
var locationPieces = body.match(locationRegex)[1].split(/[\s]/);
locationPieces.pop(); // get rid of the zipcode
var location = locationPieces.join(' ');
var description = body.match(infoRegex)[1].split(/[\s]/); // has a random newline
// example: description = [ 'Tuesday', '12:42', 'PM', 'Sunny' ]
description = description.slice(3, description.length).join(" ");
if (temperature && location && description) {
return {
location: location,
temperature: temperature,
temperatureUnit: temperatureUnit,
description: description
};
}
return "There has been an error processing this zipcode \n (could not find location, temperature or description)";
};
this.request = function (zipcode, callback) {
if (!zipcode || parseInt(zipcode, 10) > 99999 || parseInt(zipcode, 10) < 0) {
callback('Must enter a valid zipcode');
return;
}
superagent.get("https://www.google.com/search?q=weather+".concat(zipcode, "&oq=weather+").concat(zipcode)).set('Accept', 'application/json').end(function (err, res) {
if (err) {
callback(err);
} else {
var weatherObject = _this.grabTemperature(res.res.text);
if (typeof weatherObject === 'string') {
callback(weatherObject); // return error
} else {
callback(null, _this.grabTemperature(res.res.text));
}
}
});
};
};