-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlisten.js
75 lines (57 loc) · 1.51 KB
/
listen.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
var config = require('./config');
http = require('http');
fs = require('fs');
// prepare database
var mongoose = require('mongoose');
var EventSchema = mongoose.Schema({
eventObject: Object,
source: String,
timestamp: String
});
mongoose.connect(config['mongo']['url']);
var db = mongoose.connection;
// listen to POST on /
server = http.createServer(function(req, res) {
console.dir(req.param);
if (req.method == 'POST') {
console.log("POST");
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function() {
console.log("Body: " + body);
readEvent(body);
saveEvent(body);
});
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end('post received');
}
});
// create meaningful output to the console
function readEvent(json) {
var obj = JSON.parse(json);
var contextResponses = obj['contextResponses'][0]['contextElement']['attributes'];
contextResponses.forEach(function(item) {
console.log(item['name'] + ": " + item['value']);
});
}
// save event to MongoDB
function saveEvent(json) {
var obj = JSON.parse(json);
var mobj = new EventSchema({
eventObject: obj,
source: config['info']['source'],
timestamp: Date.now().toString()
});
mobj.save(function (err) {
if (err) console.log('Error: %s', err.toString());
});
}
// fire up server
port = config['server']['port'];
host = '127.0.0.1';
server.listen(port, host);
console.log('Listening at http://' + host + ':' + port);