-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
95 lines (83 loc) · 1.9 KB
/
app.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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
// Constants
const PORT = 3000;
const QUEUE_SIZE = 30;
// Setup express
const app = express();
// Setup body-parser
app.use(bodyParser.json());
// Setup cors
app.use(cors());
// Setup stats queue
let statsQueue = [];
let nextStatId = 1;
function addStat(stat) {
stat.id = nextStatId;
nextStatId += 1;
while (statsQueue.length >= QUEUE_SIZE) {
statsQueue.shift();
}
statsQueue.push(stat);
}
// Routes
// GET /
app.get('/', function (request, response) {
const body = {
message: 'Please use /api'
};
response.status(200);
response.json(body);
});
// GET /api
app.get('/api', function (request, response) {
const body = {
links: [
{
link: "/api",
description: "Returns available routes."
},
{
link: "/api/stats",
description: "GET or POST stats data."
}
]
};
response.status(200);
response.json(body);
});
function containsNewerThan(query) {
if (query !== {}) {
if (!isNaN(query.newerThan)) {
return true;
}
}
return false;
}
// GET /api/stats
app.get('/api/stats', function (request, response) {
let body = [].concat(statsQueue);
const query = request.query;
if (containsNewerThan(query)) {
var id = query.newerThan;
body = body.filter(
stat => stat.id > id
);
}
body.reverse();
response.status(200);
response.json(body);
});
// POST /api/stats
app.post('/api/stats', function (request, response) {
const stat = request.body;
// TODO: Validation
addStat(stat);
response.status(201);
response.json(stat);
});
// Run app
app.listen(PORT, function () {
console.log(`Server running on port ${PORT}`);
});