-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
67 lines (57 loc) · 1.79 KB
/
server.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
'use strict';
const app = require('koa')();
const co = require('co');
const router = require('koa-router')();
const database = require('./database');
co(function *main() {
const db = yield database.init();
router
.get('/', function *getRecords() {
this.body = { status: 'running' }
})
// returns array of all ids (= RecordReferences)
.get('/records', function *getRecords() {
const updatedAfter = this.request.query.updatedAfter;
const compact = this.request.query.compact === 'true';
const queryStr = `SELECT ${compact ? 'id, timestamp' : '*'} FROM oapen_data`;
let data;
if (updatedAfter) {
data = yield db.query(`${queryStr} WHERE timestamp >= $1`, [updatedAfter]);
} else {
data = yield db.query(queryStr);
}
this.body = data.rows;
})
// returns object (id, timestamp, data) of record with corresponding id
.get('/records/:id', function *getRecord() {
const selectData = 'SELECT * FROM oapen_data WHERE id = $1::int';
const id = parseInt(this.params.id, 10);
if (!Number.isInteger(id) || id < 0 || id > (Math.pow(2, 31) - 1)) {
this.body = {
code: '422',
message: 'Unprocessable Entity',
};
this.status = 422;
return;
}
const resp = yield db.query(selectData, [this.params.id]);
if (resp.rows.length === 0) {
this.body = {
code: '404',
message: 'Not Found',
};
this.status = 404;
return;
}
this.body = resp.rows[0];
});
app
.use(router.routes())
.use(router.allowedMethods());
const port = process.env.PORT || 3000;
app.listen(port);
console.log('App now running on port', port);
}).catch(error => {
console.error(error);
process.exit(1);
});