-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlvl.js
55 lines (51 loc) · 1.64 KB
/
lvl.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
var Level = require("level");
var nThen = require('nthen');
var getIndex = function(db, cName, cb) {
db.get(cName+'=>index', function(e, out){
if (e) {
if (e.notFound) {
cb(-1);
} else {
throw e;
}
return;
}
cb(parseInt(out));
});
};
var insert = function (db, channelName, content, cb) {
var index;
nThen(function (waitFor) {
getIndex(db, channelName, waitFor(function (i) { index = i+1; }));
}).nThen(function (waitFor) {
db.put(channelName+'=>'+index, content, waitFor(function (e) { if (e) { throw e; } }));
}).nThen(function (waitFor) {
db.put(channelName+'=>index', ''+index, waitFor(function (e) { if (e) { throw e; } }));
}).nThen(cb);
};
var getMessages = function (db, channelName, msgHandler) {
var index;
nThen(function (waitFor) {
getIndex(db, channelName, waitFor(function (i) { index = i; }));
}).nThen(function (waitFor) {
var again = function (i) {
db.get(channelName + '=>' + i, waitFor(function (e, out) {
if (e) { throw e; }
msgHandler(out);
if (i < index) { again(i+1); }
}));
};
if (0 < index) { again(0); }
});
};
module.exports.create = function (conf, cb) {
var db = Level(conf.levelPath || './test.level.db');
cb({
message: function (channelName, content, cb) {
insert(db, channelName, content, cb);
},
getMessages: function (channelName, msgHandler) {
getMessages(db, channelName, msgHandler);
}
});
};