-
Notifications
You must be signed in to change notification settings - Fork 8
/
CognicityServer.js
394 lines (356 loc) · 14 KB
/
CognicityServer.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
'use strict';
// Validation module, parameter validation functions
var Validation = require('./Validation.js');
/**
* A CognicityServer object queries against the cognicity database and returns data to be returned
* to the client via the REST service.
* @constructor
* @param {config} config The server configuration object loaded from the configuration file
* @param {object} logger Configured Winston logger instance
* @param {object} pg Configured PostGres 'pg' module instance
*/
var CognicityServer = function(
config,
logger,
pg
){
this.config = config;
this.logger = logger;
this.pg = pg;
};
CognicityServer.prototype = {
/**
* Server configuration
* @type {object}
*/
config: null,
/**
* Configured Winston logger instance
* @type {object}
*/
logger: null,
/**
* Configured 'pg' module PostGres interface instance
* @type {object}
*/
pg: null,
/**
* DB query callback
* @callback DataQueryCallback
* @param {Error} err An error instance describing the error that occurred, or null if no error
* @param {object} data Response data object which is 'result.rows' from the pg module response
*/
/**
* Perform a query against the database using the parameterized query in the queryObject.
* Call the callback with error information or result information.
*
* @param {object} queryObject Query object for parameterized postgres query
* @param {string} queryObject.text The SQL query text for the parameterized query
* @param {Array} queryObject.values Values for the parameterized query
* @param {DataQueryCallback} callback Callback function for handling error or response data
*/
dataQuery: function(queryObject, callback){
var self = this;
self.logger.debug( "dataQuery: queryObject=" + JSON.stringify(queryObject) );
self.pg.connect(self.config.pg.conString, function(err, client, done){
if (err){
self.logger.error("dataQuery: " + JSON.stringify(queryObject) + ", " + err);
done();
callback( new Error('Database connection error') );
return;
}
client.query(queryObject, function(err, result){
if (err){
done();
self.logger.error( "dataQuery: Database query failed, " + err.message + ", queryObject=" + JSON.stringify(queryObject) );
callback( new Error('Database query error') );
} else if (result && result.rows){
self.logger.debug( "dataQuery: " + result.rows.length + " rows returned" );
done();
callback(null, result.rows);
} else {
// TODO Can we ever get to this point?
done();
callback( new Error('Unknown query error, queryObject=' + JSON.stringify(queryObject)) );
}
});
});
},
/**
* Get confirmed reports from the database.
* Call the callback function with error or response data.
* @param {object} options Configuration options for the query
* @param {number} options.start Unix timestamp for start of query period
* @param {number} options.end Unix timestamp for end of query period
* @param {string} options.tbl_reports Database table for confirmed reports
* @param {?number} options.limit Number of results to limit to, or null for all
* @param {DataQueryCallback} callback Callback for handling error or response data
*/
getReports: function(options, callback){
var self = this;
// Validate options
var err;
if ( !Validation.validateNumberParameter(options.start,0) ) err = new Error( "'start' parameter is invalid" );
if ( !Validation.validateNumberParameter(options.end,0) ) err = new Error( "'end' parameter is invalid" );
if ( !options.tbl_reports ) err = new Error( "'tbl_reports' option must be supplied" );
if ( !options.limit && options.limit!==null ) err = new Error( "'limit' option must be supplied" );
if (err) {
callback(err);
return;
}
// SQL
var queryObject = {
text: "SELECT 'FeatureCollection' As type, " +
"array_to_json(array_agg(f)) As features " +
"FROM (SELECT 'Feature' As type, " +
"ST_AsGeoJSON(lg.the_geom)::json As geometry, " +
"row_to_json( " +
"(SELECT l FROM " +
"(SELECT pkey, " +
"created_at at time zone 'ICT' created_at, " +
"source, " +
"status, " +
"url, " +
"image_url, " +
"title, " +
"text) " +
" As l) " +
") As properties " +
"FROM " + options.tbl_reports + " As lg " +
"WHERE created_at >= to_timestamp($1) AND " +
"created_at <= to_timestamp($2) " +
"ORDER BY created_at DESC LIMIT $3" +
" ) As f ;",
values: [
options.start,
options.end,
options.limit
]
};
// Call data query
self.dataQuery(queryObject, callback);
},
/**
* Get an individual confirmed report from the database.
* Call the callback function with error or response data.
* @param {object} options Configuration options for the query
* @param {number} options.id Unique ID for the report
* @param {string} options.tbl_reports Database table for confirmed reports
* @param {DataQueryCallback} callback Callback for handling error or response data
*/
getReport: function(options, callback){
var self = this;
// Validate options
var err;
if ( !Validation.validateNumberParameter(options.id,0) ) err = new Error( "'id parameter is invalid" );
if ( !options.tbl_reports ) err = new Error( "'tbl_reports' option must be supplied" );
if (err) {
callback(err);
return;
}
// SQL
var queryObject = {
text: "SELECT 'FeatureCollection' As type, " +
"array_to_json(array_agg(f)) As features " +
"FROM (SELECT 'Feature' As type, " +
"ST_AsGeoJSON(lg.the_geom)::json As geometry, " +
"row_to_json( " +
"(SELECT l FROM " +
"(SELECT pkey, " +
"created_at at time zone 'ICT' created_at, " +
"source, " +
"status, " +
"url, " +
"image_url, " +
"title, " +
"text) " +
" As l) " +
") As properties " +
"FROM " + options.tbl_reports + " As lg " +
"WHERE pkey = $1 " +
" ) As f ;",
values: [
options.id
]
};
// Call data query
self.dataQuery(queryObject, callback);
},
/**
* Attribute confirmed reports with the name of the containing (parent) city boundary
* Return as JSON with location of report as embedded GeoJSON
* @param {object} options Configuration options for the query
* @param {number} options.start Unix timestamp for start of query period
* @param {number} options.end Unix timestamp for end of query period
* @param {string=} options.area_name Optional name of city as filter
* @param {string} options.tbl_reports Database table for confirmed reports
* @param {string} options.polygon_layer Database table for city polygons
* @param {number=} options.limit Number of results to limit to, or null for all
* @param {DataQueryCallback} callback Callback for handling error or response data
*/
getReportsByArea: function(options, callback){
var self = this;
// Validate Options
var err;
if ( !Validation.validateNumberParameter(options.start,0) ) err = new Error( "'start' parameter is invalid" );
if ( !Validation.validateNumberParameter(options.end,0) ) err = new Error( "'end' parameter is invalid" );
if ( !options.tbl_reports ) err = new Error( "'tbl_reports' option must be supplied" );
if ( !options.polygon_layer ) err = new Error( "'polygon_layer' option must be supplied" );
if ( typeof options.limit !== 'undefined' && options.limit !== null && !Validation.validateNumberParameter(options.limit) ) err = new Error( "'limit' option must be supplied" );
if (err) {
callback(err);
return;
}
// Set default values
if ( !options.limit ) {
options.limit = null;
}
// SQL
var queryObject = {
text: "SELECT array_to_json(array_agg(row_to_json(row))) as data FROM " +
"(SELECT a.pkey, " +
"a.created_at, " +
"a.text, " +
"a.source, " +
"ST_AsGeoJSON(a.the_geom), " +
"b.area_name " +
"FROM " + options.tbl_reports + " a, " +
options.polygon_layer + " b " +
"WHERE created_at >= to_timestamp($1) AND " +
"created_at <= to_timestamp($2) AND " +
"ST_Within(a.the_geom, b.the_geom) AND " +
"($4::varchar is null or b.area_name = $4::varchar) " +
"ORDER BY created_at DESC LIMIT $3 ) row;",
values: [
options.start,
options.end,
options.limit,
options.area_name
]
};
// Call data query
self.dataQuery(queryObject, callback);
},
/**
* Get floodsensor readings.
* Call the callback function with error or response data
* @param {object} options Configuration options for the query
* @param {number} options.start Unix timestamp for the start time of first available observation
* @param {number} options.end Unix timestamp for the end time of the last available observation
* @param {string} options.tbl_sensor_data Database table for the floodsensor observations
* @param {string} options.tbl_sensor_metadata Database table for the floodsensor metadata
* @param {DataQueryCallback} callback Callback for handling error or response data
*/
getFloodsensors: function(options, callback){
var self = this;
// Validate options
var err;
if ( !Validation.validateNumberParameter(options.start,0) ) err = new Error("'start' parameter is invalid" );
if ( !Validation.validateNumberParameter(options.end,0) ) err = new Error("'end' parameter is invalid" );
if ( !options.tbl_sensor_data ) err = new Error( "'tbl_sensor_data' option must be supplied" );
if ( !options.tbl_sensor_metadata ) err = new Error( "'tbl_sensor_metadata' option must be supplied" );
if (err) {
callback(err);
return;
}
// SQL
var queryObject = {
text: "SELECT 'FeatureCollection' as type, " +
"array_to_json(array_agg(f)) as features " +
"FROM (SELECT 'Feature' as type, " +
"ST_AsGeoJSON(props.location)::json as geometry, " +
"row_to_json((props.id, props.height_above_riverbed, props.measurements)::sensor_metadata_type) as properties " +
"FROM (SELECT " +
"m.location, m.id, m.height_above_riverbed, " +
"array_to_json(array_agg((obs.measurement_time AT TIME ZONE 'AESST', obs.distance, m.height_above_riverbed - obs.distance, obs.temperature, obs.humidity)::sensor_data_type ORDER BY obs.measurement_time ASC)) as " +
"measurements " +
"FROM " +
options.tbl_sensor_data+" as obs, " +
options.tbl_sensor_metadata+" as m " +
"WHERE obs.sensor_id = m.id " +
"AND obs.measurement_time >= to_timestamp($1) " +
"AND obs.measurement_time <= to_timestamp($2) " +
"GROUP BY m.location, m.id, m.height_above_riverbed ) as props ) as f;",
values : [
options.start,
options.end
]
};
// Call data query
self.dataQuery(queryObject, callback);
},
/**
* Get floodgauge readings.
* Call the callback function with error or response data
* @param {object} options Configuration options for the query
* @param {number} options.start Unix timestamp for the start time of first available observation
* @param {number} options.end Unix timestamp for the end time of the last available observation
* @param {string} options.tbl_floodgauges Database table for the floodgauge observations
* @param {DataQueryCallback} callback Callback for handling error or response data
*/
getFloodgauges: function(options, callback){
var self = this;
// Validate options
var err;
if ( !Validation.validateNumberParameter(options.start,0) ) err = new Error("'start' parameter is invalid" );
if ( !Validation.validateNumberParameter(options.end,0) ) err = new Error("'end' parameter is invalid" );
if ( !options.tbl_floodgauges ) err = new Error( "'tbl_floodgauges' option must be supplied" );
if (err) {
callback(err);
return;
}
// SQL
var queryObject = {
text: "SELECT 'FeatureCollection' as type, " +
"array_to_json(array_agg(f)) as features " +
"FROM (SELECT 'Feature' as type, " +
"ST_AsGeoJSON(props.the_geom)::json as geometry, " +
"row_to_json((props.gaugeid, props.gaugenameid, props.observations)::prop_type) as properties " +
"FROM (SELECT " +
"the_geom, gaugeid, gaugenameid, " +
"array_to_json(array_agg((obs.measuredatetime AT TIME ZONE 'ICT', obs.depth, obs.warninglevel, obs.warningnameid)::obs_type ORDER BY obs.measuredatetime ASC)) as " +
"observations " +
"FROM " +
options.tbl_floodgauges+" as obs " +
"WHERE obs.measuredatetime >= to_timestamp($1) " +
"AND obs.measuredatetime <= to_timestamp($2) " +
"GROUP BY gaugeid, the_geom, gaugenameid ) as props ) as f;",
values : [
options.start,
options.end
]
};
// Call data query
self.dataQuery(queryObject, callback);
},
/**
* Get infrastructure details as JSON/GeoJSON response.
* @param {object} options Options object for the server query
* @param {string} options.infrastructureTableName Table name of the infrastructure table to query
* @param {DataQueryCallback} callback Callback for handling error or response data
*/
getInfrastructure: function(options, callback){
var self = this;
// Validate options
if (!options.infrastructureTableName) {
callback( new Error("Infrastructure table is not valid") );
return;
}
var queryObject = {
text: "SELECT 'FeatureCollection' AS type, " +
"array_to_json(array_agg(f)) AS features " +
"FROM (SELECT 'Feature' AS type, " +
"ST_AsGeoJSON(lg.the_geom)::json AS geometry, " +
"row_to_json( " +
"(SELECT l FROM (SELECT name) as l) " +
") AS properties " +
"FROM " + options.infrastructureTableName + " AS lg " +
") AS f;",
values: []
};
// Call data query
self.dataQuery(queryObject, callback);
}
};
//Export our object constructor method from the module
module.exports = CognicityServer;