-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
55 lines (46 loc) · 1.56 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
var config = require('./config.js')
var _ = require('lodash')
var restify = require('restify')
var bunyan = require('bunyan')
var log = bunyan.createLogger({name: config.LOG_NAME})
var isSchemaValid = require('./src/indraSchemaValidator.js')
var socketio = require('socket.io')
var fs = require('fs')
var server = restify.createServer()
server.use(restify.bodyParser())
server.use(restify.CORS())
server.use(restify.fullResponse())
// JSON post request route is named /
server.post('/', handleRequest)
server.listen(config.PORT, function () {
log.info('listening on %s', config.PORT)
})
var io = socketio.listen(server.server);
//io.set('origins', '*')
io.sockets.on('connection', function (socket) {
log.warn('client connected')
})
// sends data through socket.io
function publish (data) {
io.emit(data.type, data)
}
// extends post with {receivedAt: 'ISOString'} and saves it to db
function addReceivedAt (post) {
var d = new Date()
return _.extend(post, { receivedAt: d.toISOString() })
}
// handles JSON post requests
function handleRequest (req, res, next) {
// if valid json ->
if (isSchemaValid(req.body)) {
data = addReceivedAt(req.body) // add createdAt field
publish(data) // publish over pusher
res.send(202) // send 202
return next();
}
// bad data -> 422 UnprocessableEntityError
log.warn('bad data schema -> %s', JSON.stringify(req.body));
return next(
new restify.UnprocessableEntityError(
config.UNPROCESSABLE_ENTITY_ERROR_MESSAGE));
}