forked from mikeal/relaximation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcouchdb_changes.js
More file actions
65 lines (60 loc) · 1.83 KB
/
couchdb_changes.js
File metadata and controls
65 lines (60 loc) · 1.83 KB
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
var sys = require('sys'),
http = require('http'),
url = require('url'),
querystring = require("querystring");
String.prototype.endsWith = function(str) {return (this.match(str+"$")==str)};
var Changes = function (uri, options) {
// Accepts db name or url to _changes
if (!uri.endsWith('_changes')) {
if (!uri.endsWith('/')) { uri += '/'};
uri += '_changes';
}
if (!options) {
var options = {}
}
options.feed = 'continuous'
this.url = url.parse(uri);
this.options = options;
this.h = http.createClient(this.url.port, url.host);
this.buffer = ''
var c = this;
sys.puts(this.url.pathname+'?'+querystring.stringify(options))
var changesHandler = function (data) {
sys.puts(data)
if (data.indexOf('\n')) {
var chunks = data.split('\n');
if (c.buffer) {
chunks[0] = c.buffer + chunks[0];
c.buffer = null;
}
} else {
if (c.buffer) {
data = c.buffer + data;
c.buffer = null;
}
var chunks = [data];
}
for (i = 0; i < chunks.length; i += 1) {
var chunk = chunks[i];
if (chunk) {
try {
var obj = JSON.parse(chunk);
} catch(e) {
if (i != (chunks.length -1)) {
throw "For some reason I think this is a chunk "+chunk;
} else {
c.buffer = chunk;
}
}
if (obj) { c.emit('change', obj); }
}
}
}
this.h.request("GET", this.url.pathname+'?'+querystring.stringify(options),
{'accept':'application/json'})
.finish(function(response) {response.addListener('body', changesHandler)});
}
sys.inherits(Changes, process.EventEmitter);
exports.Changes = Changes;
// var test = new Changes('http://localhost:5984/testbot/_changes');
// test.addListener('change', function (obj) {sys.puts(JSON.stringify(obj))});