-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
83 lines (78 loc) · 2.41 KB
/
index.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
const http = require("https");
const xml2js = require("xml2js");
const rejectWithStack = (reject, message, error) => {
const result = new Error(`${message}: ${error.message}`);
result.stack = error.stack;
return reject(result);
};
const downloadData = () =>
new Promise((resolve, reject) => {
const errorHandler = rejectWithStack.bind(
null,
reject,
"Unable to receive data"
);
const requestHandler = (response) => {
let body = "";
response.on("data", (chunk) => (body += chunk));
response.on("end", () => resolve(body));
response.on("error", errorHandler);
};
const requestOptions = {
host: "niagararegion.ca",
path: "/sherpa-lists/beach-results_v4.xml",
port: 443,
};
const request = http.request(requestOptions, requestHandler);
request.on("error", errorHandler);
request.end();
});
const parseData = (data) =>
new Promise((resolve, reject) => {
new xml2js.Parser()
.parseStringPromise(data)
.then((result) => {
try {
const beaches = result.rs.bm
.map(
({
$: {
ows_Beach_Id: idString,
ows_Beach_Name: name,
ows_Posting_Date: datePosted,
ows_Posting_Reason: reason,
ows_Posting_Status: status,
ows_Survey_Date: dateSurveyed,
ows_Survey_Temp: temperatureString,
},
}) => {
const id = parseInt(idString, 10);
const temperature = parseFloat(temperatureString);
return {
datePosted,
dateSurveyed,
id: isNaN(id) ? undefined : id,
name,
reason,
status,
temperature: isNaN(temperature) ? undefined : temperature,
};
}
)
.sort((a, b) => {
if (a.name > b.name) return 1;
if (b.name > a.name) return -1;
return 0;
});
return resolve(beaches);
} catch (error) {
return rejectWithStack(reject, "Unable to parse data", error);
}
})
.catch((error) => {
rejectWithStack(reject, "Unable to parse data", error);
});
});
module.exports = {
fetchAll: () => downloadData().then(parseData),
};