-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathservedata.js
More file actions
297 lines (283 loc) · 8.23 KB
/
servedata.js
File metadata and controls
297 lines (283 loc) · 8.23 KB
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
/* jshint node: true */
/* global require, console, __dirname */
'use strict';
var express = require('express'),
bodyParser = require('body-parser'),
dataAccess = require('./dataAccess'),
models = require('./models'),
swaggerValidator = require('swagger-model-validator'),
settings = require('./client-settings.js'),
util = require('util'),
queryString = require('qs');
var app = express();
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET');
res.header('Access-Control-Allow-Methods', 'DELETE');
res.header('Access-Control-Allow-Headers', ['Content-Type', 'x-api-key']);
next();
};
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(allowCrossDomain);
var swagger = require('swagger-node-express').createNew(app);
swaggerValidator(swagger);
var checkApiKey = function(request, response, next) {
var keySent = request.query.api_key || request.headers['x-api-key'];
if (keySent !== settings.apiKey) {
response.status(401);
return response.send({'success': false, 'error': 'Incorrect/Missing API Key'});
}
return next();
};
var handleError = function(err, response) {
console.log(err.message);
response.status(400);
response.send(err);
};
var getReadings = function(params, response) {
var validation = swagger.validateParams(getAll.spec, params, true);
if (!validation.valid) {
return response.send(validation.GetFormattedErrors());
}
dataAccess.getReadings(params, function (err, results){
if (err){
handleError(err, response);
} else {
response.status(200);
response.send(results);
}
});
};
var getCategories = {
'spec': {
'description' : 'Get data categories',
'path' : '/todmorden/categories/',
'notes' : 'Returns categories of data, i.e. sensor names and message types.',
'summary' : 'Get categories',
'method': 'GET',
'nickname' : 'getCategories'
},
action: function (request, response) {
dataAccess.getCategories(function (err, results){
if (err){
handleError(err, response);
} else {
response.status(200);
response.send(results);
}
});
}
};
var infoAboutGettingData =
'Parameter dates are accepted in local time, data is returned in UTC.' +
'An optional limit is accepted and returns the most recent records.' +
'Data is measured for some sensors every second, and for others every 10 minutes,' +
'But it is only recorded on change, apart from at 00.05, when all data is recorded.';
var getAll = {
'spec': {
'description' : 'Get all data',
'path' : '/todmorden/all/',
'notes' :
'Returns all data from all sensors and all messages.' + infoAboutGettingData,
'summary' : 'Get all data',
'method': 'GET',
'parameters' : [{
'paramType': 'query',
'name': 'from',
'required': false,
'type': 'string',
'description': 'Start date - YYYY-MM-DD',
'format': 'date',
}, {
'paramType': 'query',
'name': 'to',
'required': false,
'type': 'string',
'description': 'End date - YYYY-MM-DD',
'format': 'date',
}, {
'paramType': 'query',
'name': 'limit',
'required': false,
'type': 'integer',
'description': 'How many records to return (blank = all)',
}],
'type' : 'array',
'items': {
$ref: 'Reading'
},
'errorResponses' : [
swagger.errors.invalid('from'),
swagger.errors.invalid('to'),
],
'nickname' : 'getAll'
},
action: function (request, response) {
var params = queryString.parse(request.query);
return getReadings(params, response);
}
};
var getByCategory = {
'spec': {
'description' : 'Get data from single category',
'path' : '/todmorden',
'notes' :
'Returns data from specified category (sensor or message type)' + infoAboutGettingData,
'method': 'GET',
'parameters' : [{
name: 'category',
description: 'Category (sensor or message)',
type: 'string',
required: true,
enum: [
'Air Temperature',
'Water Temperature',
'Light',
'Humidity',
'pH',
'pHmV',
'Digital Water Level',
'Water Pump Current',
'Air Pump 1 Current',
'Air Pump 2 Current',
'Light_Voltage',
'Humidity_Voltage',
'pH_Voltage',
'system',
'Valve Messages',
'Valve Mode'
],
defaultValue: undefined,
paramType: 'query'
},{
'paramType': 'query',
'name': 'from',
'required': false,
'type': 'string',
'description': 'Start date - YYYY-MM-DD',
'format': 'date',
}, {
'paramType': 'query',
'name': 'to',
'required': false,
'type': 'string',
'description': 'End date - YYYY-MM-DD',
'format': 'date',
}, {
'paramType': 'query',
'name': 'limit',
'required': false,
'type': 'integer',
'description': 'How many records to return (blank = all)',
}],
'type' : 'array',
'items': {
$ref: 'Reading'
},
'errorResponses' : [
swagger.errors.invalid('from'),
swagger.errors.invalid('to'),
],
'nickname' : 'getByCategory'
},
action: function (request, response) {
var params = queryString.parse(request.query);
return getReadings(params, response);
}
};
var postReading = {
'spec': {
'description' : 'Post a reading in a single category',
'path' : '/todmorden',
'notes' :
'Records data in specified category (sensor or message type).' +
'Date must be in ISO format',
'method': 'POST',
'parameters' : [{
'paramType': 'form',
'name': 'sensor_name',
'required': true,
'type': 'string',
'description': 'Category, for example name of sensor or "system" etc'
}, {
'paramType': 'form',
'name': 'reading_time',
'required': true,
'type': 'string',
'format': 'date-time',
'description': 'When the reading was taken. Dates without times default to midnight'
}, {
'paramType': 'form',
'name': 'reading_value',
'required': true,
'type': 'string',
'description': 'The reading value (without units) or message content'
}],
'errorResponses' : [
swagger.errors.invalid('date'),
],
'nickname' : 'postReading'
},
action: function (request, response) {
checkApiKey(request, response, function() {
var validation = swagger.validateModel('Reading', request.body);
if (!validation.valid) {
response.status(405);
return response.send(validation.GetFormattedErrors());
}
dataAccess.createReading(request.body, function (err, result){
if (err){
console.log('Can\'t create reading: '+err.message);
response.status(400);
response.send(err);
} else {
response.status(201);
response.send({id: result.insertId});
}
});
});
}
};
var deleteReading = {
'spec': {
'description' : 'Delete a reading',
'path' : '/todmorden/{id}',
'notes' :
'Records data in specified category (sensor or message type).' +
'Date must be in ISO format',
'method': 'POST',
'parameters' : [{
'paramType': 'path',
'name': 'id',
'required': true,
'type': 'string',
'description': 'Delete the reading with this id'
}],
'nickname' : 'deleteReading'
},
action: function (request, response) {
checkApiKey(request, response, function() {
dataAccess.deleteReading(request.params.id, function (err, result){
if (err){
console.log('Can\'t delete reading: '+err.message);
response.status(400);
response.send(err);
} else {
response.status(200);
response.send({success: true});
}
});
});
}
};
swagger.addModels(models)
.addGet(getCategories)
.addGet(getAll)
.addGet(getByCategory)
.addPost(postReading)
.addDelete(deleteReading);
swagger.configure(settings.baseUrl + ':' + settings.port, '0.1');
app.use(express.static(__dirname + '/node_modules/swagger-node-express/swagger-ui/'));
app.listen(settings.port);
console.log('Aqua API Server running on '+settings.port);