Fix #19 by adding a lock to level db connector

This commit is contained in:
Caleb James DeLisle 2016-04-20 14:38:15 +02:00
parent 5db487db3f
commit e68dd31a53
1 changed files with 21 additions and 7 deletions

View File

@ -17,13 +17,25 @@ var getIndex = function(db, cName, cb) {
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 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();
}
};
var getMessages = function (db, channelName, msgHandler) {
@ -44,6 +56,8 @@ var getMessages = function (db, channelName, msgHandler) {
module.exports.create = function (conf, cb) {
var db = Level(conf.levelPath || './test.level.db');
db.locked = false;
db.queue = [];
cb({
message: function (channelName, content, cb) {
insert(db, channelName, content, cb);