-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
179 lines (156 loc) · 4.47 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
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
require("dotenv").config();
const pg = require("pg");
const { Client } = pg;
const {
MANUAL_RIVERS,
SERVICE_BASEURL,
USGS_URL,
DEFAULT_PERIOD,
DATABASE_URL,
} = process.env;
const client = new Client({
connectionString: DATABASE_URL,
});
async function getRiver(uuid) {
return fetch(`${SERVICE_BASEURL}/api/v1/rivers/${uuid}`)
.then((res) => {
if (!res.ok) {
throw res;
}
return res.json();
})
.then((data) => data)
.catch((errorRes) => {
console.error(`Something went wrong, error with code ${errorRes.status}`);
});
}
async function getRivers() {
return fetch(`${SERVICE_BASEURL}/api/v1/rivers`)
.then((res) => {
if (!res.ok) {
throw res;
}
return res.json();
})
.then((data) => data)
.catch((errorRes) => {
console.error(`Something went wrong, error with code ${errorRes.status}`);
});
}
async function getUsgsWaterReport(siteCodes, period = DEFAULT_PERIOD) {
// Fetches water data from USGS. In JSON format.
// Queries all the site codes over the period.
// Parameter code will fetch only discharge for now
return fetch(
`${USGS_URL}?format=json,1.1&sites=${siteCodes}&period=${period}¶meterCd=00060`
)
.then((res) => {
if (!res.ok) {
throw res;
}
return res.json();
})
.then((data) => data)
.catch((errorRes) => {
console.error(`Something went wrong, error with code ${errorRes.status}`);
});
}
function parseWaterReportResultsForSiteCodes(results, riverSiteCodeIdLookup) {
/*
{
'<river uuid>': [{
timestamp: '12345',
discharge: '123.4',
riverId: '123'
}]
}
*/
const riverWithFlowsDict = {};
for (const entry of results.value.timeSeries) {
const siteCode = entry?.sourceInfo?.siteCode?.[0]?.value;
const unit = entry?.variable?.unit?.unitCode;
const values = entry?.values?.[0].value.reduce((acc, v) => {
const jsDate = new Date(v.dateTime);
const minutes = jsDate.getMinutes();
// Only include on the hour data
if (minutes === 0) {
acc = [
...acc,
{
timestamp: jsDate.toUTCString(),
value: parseFloat(v.value).toFixed(2),
unit,
},
];
}
return acc;
}, []);
const riverId = riverSiteCodeIdLookup[siteCode];
riverWithFlowsDict[riverId] = values;
}
return riverWithFlowsDict;
}
function createSQLInsertStatement(riverIdsFlowsDict) {
const insertStatementPrefix =
"INSERT INTO water_reports (timestamp, discharge, river_id) VALUES";
const values = Object.entries(riverIdsFlowsDict).reduce(
(acc, [riverId, flows]) => {
const formattedFlows = flows.map(
(flow) => `('${flow.timestamp}', ${flow.value}, '${riverId}')`
);
if (formattedFlows.length > 0) {
acc = `${acc.length > 0 ? `${acc},` : acc}${formattedFlows.join(",")}`;
}
return acc;
},
""
);
return `${insertStatementPrefix} ${values}`;
}
async function syncRivers(rivers) {
const stateSiteCodesDict = {};
const riverSiteCodeIdDict = {};
for (const river of rivers) {
stateSiteCodesDict[river.stateAbbr] = [
...(stateSiteCodesDict[river.stateAbbr] || []),
river.siteCode,
];
riverSiteCodeIdDict[river.siteCode] = river.uuid;
}
// Dictionary with keys being river ids
// Values are an array of flows for a given river
let riverFlowsDict = {};
// Iterate over each key (state) in stateSiteCodesDict
for (const abbr in stateSiteCodesDict) {
// Water reports for the site codes
const waterReports = await getUsgsWaterReport(stateSiteCodesDict[abbr]);
riverFlowsDict = {
...riverFlowsDict,
...parseWaterReportResultsForSiteCodes(waterReports, riverSiteCodeIdDict),
};
}
const combinedSqlInsertStatement = createSQLInsertStatement(riverFlowsDict);
await client.connect();
try {
await client.query(combinedSqlInsertStatement);
} catch (err) {
console.log(err);
}
await client.end();
}
async function main() {
const manualRiverUuids = MANUAL_RIVERS?.split(",") || [];
// If there are manual rivers, sync those instead of all rivers
if (manualRiverUuids.length) {
let rivers = [];
for (const manualRiverUuid of manualRiverUuids) {
const river = await getRiver(manualRiverUuid);
rivers = [...rivers, river];
}
syncRivers(rivers);
} else {
const rivers = await getRivers();
syncRivers(rivers);
}
}
main();