cryptpad/storage/lvl.js

74 lines
2.1 KiB
JavaScript
Raw Normal View History

2016-02-11 11:28:05 +00:00
var Level = require("level");
var nThen = require('nthen');
2016-02-11 11:28:05 +00:00
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));
2016-02-11 11:28:05 +00:00
});
};
2016-02-11 11:28:05 +00:00
var insert = function (db, channelName, content, cb) {
var index;
var doIt = function () {
db.locked = true;
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(function (waitFor) {
db.locked = false;
if (!db.queue.length) { return; }
db.queue.shift()();
}).nThen(cb);
};
if (db.locked) {
db.queue.push(doIt);
} else {
doIt();
}
2016-02-11 11:28:05 +00:00
};
2016-04-21 15:01:21 +00:00
var getMessages = function (db, channelName, msgHandler, cb) {
2016-02-11 11:28:05 +00:00
var index;
nThen(function (waitFor) {
2016-04-21 17:03:22 +00:00
getIndex(db, channelName, waitFor(function (i) {
index = i;
}));
2016-02-11 11:28:05 +00:00
}).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); }
2016-04-21 15:01:21 +00:00
else if (cb) { cb(); }
2016-02-11 11:28:05 +00:00
}));
};
if (index > -1) { again(0); }
2016-04-21 17:03:22 +00:00
else if (cb) { cb(); }
2016-02-11 11:28:05 +00:00
});
};
2016-02-11 11:28:05 +00:00
module.exports.create = function (conf, cb) {
var db = Level(conf.levelPath || './test.level.db');
db.locked = false;
db.queue = [];
cb({
2016-02-11 11:28:05 +00:00
message: function (channelName, content, cb) {
insert(db, channelName, content, cb);
},
2016-04-21 15:01:21 +00:00
getMessages: function (channelName, msgHandler, cb) {
getMessages(db, channelName, msgHandler, cb);
2016-02-11 11:28:05 +00:00
}
});
};