This repository has been archived by the owner on Dec 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
weatherQuery.js
60 lines (53 loc) · 1.88 KB
/
weatherQuery.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
'use strict';
const http = require('http');
const xml2JS = require('xml2js');
const { WeatherData } = require('./model/data');
// this one will handle httpResponse
// if response status code is 200, we're good to go
// if 301, then it's a redirect, then we try to handle so, by using redirected
// url otherwise, upto current situation, we can assume other status code will
// be treated as error, and won't be handled
function _handler(res, resolve, reject) {
if (res.statusCode === 301) {
if (res.headers.location !== undefined && res.headers.location !== null)
http.get(res.headers.location, (res) => _handler(res, resolve, reject)); // in case of redirection
} else if (res.statusCode === 200) {
let data = '';
res.on('data', (chunk) => {
data += chunk; // keeps reading data
});
res.on('end', () => { // when data flow ends, parses XML response to JSON
xml2JS.parseString(data, (err, result) => {
if (err !== undefined && err !== null)
reject('error');
else
resolve(WeatherData.fromJSON(
result.weatherdata)); // this is where main data extraction is
// done
});
}).on('error', (err) => { reject('error'); });
} else {
res.resume();
reject('response not ok');
}
}
// Queries are made using this function
// *** URL passed to function doesn't need to be URI encoded, it'll be done internally
// So be careful with that :)
function query(url) {
return new Promise((resolve, reject) => {
try {
http.get(encodeURI(url), (res) => _handler(res, resolve, reject));
} catch (e) {
console.log(e);
reject('error');
}
});
}
module.exports = query;
// following section was used for testing purposes
/*
query(
"http://yr.no/place/Pakistan/Khyber_Pakhtunkhwa/Swāt_District/forecast.xml")
.then((data) => console.log(data.toJSON()), (err) => console.log(err));
*/