-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
87 lines (69 loc) · 2.28 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
const express = require('express');
const bodyParser = require("body-parser");
const lib = require('./lib');
const cors = require('cors')
// Express App starts from here.
let app = express();
const maxRequestSize = 100; // 100KB of publish is allowed at max.
app.use(bodyParser.json({ limit: maxRequestSize * 1024 }));
app.use(cors());
app.get('/', function (req, res) {
res.status(200).end("ROOT");
});
// AutoIncrement clientId.
let clientId = 0;
// Subscribe endpoint. This endpoint is used to subscribe
// to one or more channels.
app.get('/subscribe', function (req, res) {
if(!req.query.channels) {
res.status(400).end("Bad Request");
return;
}
// Get channelNames from the query params
// get auto incremented clientId.
const channelNames = req.query.channels.split(',');
const newClientId = req.query.clientId ? req.query.clientId : ++clientId;
// Reister client.
lib.registerClient(channelNames, newClientId, req, res);
});
app.get('/lastEvent', function (req, res) {
if(!req.query.channel) {
res.status(400).end("Bad Request");
return;
}
const channelName = req.query.channel;
// Get last event
const response = lib.getLastEvent(channelName);
res.status(200).json({ response });
});
app.post('/publish/', function(req, res) {
let { events } = req.body;
if(!events) {
events = [];
}
// Validation for any reserved events.
for(const event of events) {
const { type } = event;
if(lib.reservedEvents.includes(type)) {
res.status(400).end(`Event type "${type}" is reserved, can't fire!`);
return;
}
}
// Now fire all events.
for(const event of events) {
const {channelName, type, payload} = event;
if(!channelName || !type || !payload) {
res.status(400).end("Bad Request: 'channelName', 'type', and 'payload' are three required json fields in an event.");
}
try {
lib.publishDataToChannel(channelName, type, payload);
} catch(err) {
console.log(err);
errors.push(err.message);
}
}
res.status(200).end();
});
app.listen(process.env.PORT || 9090, () => {
console.log(`Server listening on port: ${process.env.PORT || 9090}`);
});