-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
83 lines (67 loc) · 2.59 KB
/
worker.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
var sys = require('sys');
var noderouter = require('./lib/node-router');
var querystring = require('querystring');
var lpb = require('./lib/longpollingbuffer');
var uuid = require('./lib/uuid');
var server = noderouter.getServer();
var url = require('url');
var validhash = '.[0-9A-Za-z_\-]*';
var buffersize = 40;
var feeds = {};
//Create a feed
server.post("/__create", function (req, res, poststring) {
res.sendHeader(200,{"Content-Type": "application/json"});
//grab the hash from the query string
postvals = querystring.parse(poststring);
if(postvals.hasOwnProperty('hash')){
feeds[postvals.hash] = new lpb.LongPollingBuffer(buffersize);
res.write('{"status" : "success", "feed" : "'+postvals.hash+'" }' );
}
else {
res.write("{'status':'error', 'message':'must provide a hash for the feed to be created'}" );
}
res.end();
}, "form-url-encode");
//insert data into a feed
server.post(new RegExp("^/insert/("+validhash+")$"), function(req,res,hash,poststring){
sys.puts("hash = " + hash);
sys.puts("postJSON = " + sys.inspect(querystring.parse(poststring)));
res.sendHeader(200,{"Content-Type": "application/json"});
//if the feed exists go ahead and insert the item into the buffer
if(feeds.hasOwnProperty(hash)){
toinsert = cleaninsert(querystring.parse(poststring));
buffer = feeds[hash].push(toinsert);
res.write("{'status':'success', 'inserted': "+JSON.stringify(toinsert)+"}");
}
else{
res.write("{'status':'error', 'message':'invalid feed identifier'}");
}
res.end();
}, "form-url-encode");
//Get updates on a feed
server.get(new RegExp("^/latest/("+validhash+")$"), function (req, res, hash) {
//first check to verify that the feed exists
if(!feeds.hasOwnProperty(hash)){
return {status:'error', message:'invalid feed identifier'};
}
buffer = feeds[hash];
var thesince;
if(url.parse(req.url,true).hasOwnProperty('query') && url.parse(req.url,true).query.hasOwnProperty('since')){
thesince = parseInt(url.parse(req.url,true)['query']['since']);
}
else {
thesince = -1;
}
sys.puts('The Since = ' + thesince);
buffer.addListenerForUpdateSince(thesince, function(data){
var body = '['+data.map(JSON.stringify).join(',\n')+']';
res.sendHeader(200,{"Content-Type": "text/html"});
res.write( body );
res.close();
});
});
var cleaninsert = function(toinsert){
//this is where we trim down the item to be within the terms of use
return toinsert;
}
server.listen(8081);