-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
59 lines (56 loc) · 2.04 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
54
55
56
57
58
59
var http = require('http');
var level = require('level');
var db = level(__dirname + '/data', { encoding: 'json' });
var ecstatic = require('ecstatic')(__dirname + '/static');
var qs = require('querystring');
var dehumanize = require('dehumanize-date');
var lexi = require('lexicographic-integer');
var through = require('through');
var concat = require('concat-stream');
var server = http.createServer(function (req, res) {
var parts = req.url.split('?')[0].split('/').slice(1)
.map(function (p) { return decodeURIComponent(p) })
;
if (req.method === 'POST' && parts[1] === 'timeline.json') {
req.pipe(concat(function (body) {
try { var doc = JSON.parse(body) }
catch (e) {
res.statusCode = 400;
return res.end(e.message + '\n');
}
if (!doc) {
res.statusCode = 400;
return res.end('unexpected document\n');
}
var t = String(doc.time).trim().toLowerCase() === 'now'
? new Date : dehumanize(doc.time)
;
var user = parts[0];
var key = user + '!' + lexi.pack(Math.floor(t / 1000), 'hex');
db.put(key, doc);
}));
}
else if (req.method === 'GET' && parts[1] === 'timeline.json') {
res.setHeader('content-type', 'application/newline-delimited-json');
var opts = {
start: parts[0],
end: parts[0] + '\uffff',
encoding: 'utf8'
};
db.createReadStream(opts).pipe(through(function (row) {
var sp = row.key.split('!');
var doc = {
user: sp[0],
time: lexi.unpack(sp[1]),
timetext: row.value.time,
text: row.value.text
};
this.queue(JSON.stringify(doc) + '\n');
})).pipe(res);
}
else ecstatic(req, res)
});
server.listen(process.env.PORT || 8000);
server.on('listening', function () {
console.log('listening on :' + server.address().port);
});