-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·63 lines (54 loc) · 1.8 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
/* global require:true, console:true, process:true, __dirname:true */
'use strict'
// Example run command: `node app.js 9000 6380 true`; listen on port 9000, connect to redis on 6380, debug printing on.
var express = require('express'),
http = require('http'),
redis = require('redis'),
redisClient,
port = process.argv[2] || 80,
rport = process.argv[3] || 6379,
debug = process.argv[4] || null
// Database setup
redisClient = redis.createClient(rport)
redisClient.on('connect', function() {
console.log('Connected to redis.')
})
// Data handling
var save = function save(d) {
redisClient.hmset(d.postId, d)
if (debug)
console.log('saved to redis: ' + d.postId + ', at: ' + (new Date()).toString())
}
// Server setup
var app = express()
app.use(express.bodyParser())
app.use(express.static(__dirname + '/public'))
// Handle POSTs from frontend
app.post('/', function handlePost(req, res) {
// Get experiment data from request body
var d = req.body
// If a postId doesn't exist, add one (it's random, based on date)
if (!d.postId) d.postId = (+new Date()).toString(36)
// Add a timestamp
d.timestamp = (new Date()).getTime()
// Save the data to our database
save(d)
// Send a 'success' response to the frontend
res.send(200)
})
// On access to /participantCount, return current number of keys
app.get('/participantCount', function handleGet(req, res) {
var finish = function(d) {
res.json(d)
}
// get all keys from redis
redisClient.keys("*", function(err, res) {
finish({
participantCount: res.length
})
});
})
// Create the server and tell which port to listen to
http.createServer(app).listen(port, function(err) {
if (!err) console.log('Listening on port ' + port)
})