-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode-yahoo-weather.js
269 lines (212 loc) · 6.2 KB
/
node-yahoo-weather.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
'use strict';
const request = require('request-promise');
const yahooConditions = require('./yahoo-conditions');
const EventEmitter = require('events');
class YahooWeather extends EventEmitter {
constructor(options) {
super();
// Set defaults
this.temp_metric = options.temp_metric;
this.latitude = options.latitude;
this.longitude = options.longitude;
this.location = options.location;
this.reverseGeoLocation = options.reverseGeoLocation;
// Start polling for information
if (options.polling) {
this._startPolling();
}
// Expose yahoo weather queries
this.queries = function createQueries(location) {
return {
forecast: `select * from weather.forecast where woeid in (select woeid from geo.places(1)
where text="${location}") and u="${this.temp_metric}"`,
current: `select * from weather.forecast where woeid in (select woeid from geo.places(1)
where text="${location}") and u="f"`,
};
};
}
_queryYahooAPI(weatherYQL) {
// Make request to fetch weather information from yahoo
return request(weatherYQL);
}
getConditionMetadata(code) {
// Get metadata belonging to weather code
return yahooConditions[(code === '3200') ? 48 : code];
}
fetchData() {
// Return promise
return new Promise((resolve, reject) => {
new Promise(locationResolve => {
// If lat long provided, do reverse geocoding
if (this.latitude && this.longitude) {
// Resolve with lat lng object found in speech
locationResolve(`(${this.latitude},${this.longitude})`);
} else {
// Resolve with location object found in speech
locationResolve(this.location);
}
}).then(location => {
// Make two queries simultaneously
Promise.all([this._queryForecasts(location), this._queryCurrent(location)]).then(data => {
if (data[0] && data[1]) {
// Correct for wrong metric format by yahoo
data[0].atmosphere = data[1].atmosphere;
// Resolve
resolve(this._parseData(data[0]));
} else {
// Error
reject();
}
}).catch(err => reject(err));
});
});
}
_queryForecasts(location) {
return new Promise((resolve, reject) => {
// Make the weather api request
this._queryYahooAPI(`https://query.yahooapis.com/v1/public/yql?q=${encodeURIComponent(this.queries(location).forecast)}&format=json`)
.then((data1) => {
const jsonData = JSON.parse(data1);
// If no data provided, try again
if (!jsonData.query.results) {
// Make the weather api request
this._queryYahooAPI(`https://query.yahooapis.com/v1/public/yql?q=${encodeURIComponent(this.queries(location).forecast)}&format=json`)
.then((data2) => {
if (JSON.parse(data2).query.results) {
// Resolve with data
resolve(JSON.parse(data2).query.results.channel);
} else reject('no_info_location');
})
.catch((err) => {
// Reject
reject(err);
});
} else {
// Resolve with data
resolve(jsonData.query.results.channel);
}
}).catch((err) => {
// Reject
reject(err);
}
);
});
}
_queryCurrent(location) {
return new Promise((resolve, reject) => {
// Make the weather api request
this._queryYahooAPI(`https://query.yahooapis.com/v1/public/yql?q=${encodeURIComponent(this.queries(location).current)}&format=json`)
.then((data1) => {
const jsonData = JSON.parse(data1);
// If no data provided, try again
if (!jsonData.query.results) {
// Make the weather api request
this._queryYahooAPI(`https://query.yahooapis.com/v1/public/yql?q=${encodeURIComponent(this.queries(location).current)}&format=json`)
.then((data2) => {
if (JSON.parse(data2).query.results) {
// Resolve with data
resolve(JSON.parse(data2).query.results.channel);
} else reject('no_info_location');
})
.catch((err) => {
// Reject
reject(err);
});
} else {
// Resolve with data
resolve(jsonData.query.results.channel);
}
}).catch((err) => {
// Reject
reject(err);
}
);
});
}
_parseData(data) {
// If no data found throw error
if (!data) throw Error('no data');
const forecasts = data.item.forecast;
// Loop over all forecasts
for (const x in forecasts) {
if (forecasts[x].code) {
// Retrieve metadata
const metadata = this.getConditionMetadata(forecasts[x].code);
// Merge the objects
Object.assign(forecasts[x], metadata);
}
}
// Construct current object
const current = {
wind: data.wind,
atmosphere: data.atmosphere,
astronomy: data.astronomy,
code: data.item.condition.code,
temperature: data.item.condition.temp,
};
// Get metadata for current
const metadata = this.getConditionMetadata(current.code);
// Merge the objects
Object.assign(current, metadata);
return {
current: current,
forecasts: forecasts,
};
}
_startPolling() {
// Refresh data every 60 seconds
setInterval(() => {
this.fetchData().then((data) => {
// Construct updated data set
const newData = {
wind: data.current.wind,
atmosphere: data.current.atmosphere,
astronomy: data.current.astronomy,
temperature: data.current.temperature,
weatherType: data.current.type,
};
// Iterate over first level
for (const x in this.data) {
// Check for more levels
if (typeof this.data[x] === 'object') {
// Loop over second level
for (const y in this.data[x]) {
if (this.data[x][y] !== newData[x][y]) {
this.emit(`${x}_${y}`, newData[x][y]);
}
}
} else {
if (this.data[x] !== newData[x]) {
this.emit(x, newData[x]);
}
}
}
// Update data set
this.data = newData;
});
}, 30000);
}
get(attribute, callback) {
if (attribute) {
const attrs = attribute.split('_');
let result;
if (this.data) {
if (attrs.length > 0) {
if (this.data[attrs[0]]) {
result = this.data[attrs[0]][attrs[1]];
} else {
callback(true, false);
}
} else {
result = this.data[attrs[0]];
}
callback(null, result);
} else {
callback(true, false);
}
} else {
callback(true, false);
}
}
}
module.exports = YahooWeather;