Fix the lvl storage

pull/1/head
Caleb James DeLisle 9 years ago
parent 350c9e6c76
commit dff8143fad

@ -4,6 +4,8 @@
"version": "0.1.0",
"dependencies": {
"express": "~4.10.1",
"ws": "^1.0.1"
"ws": "^1.0.1",
"level": "~1.4.0",
"nthen": "~0.1.0"
}
}

@ -1,77 +1,48 @@
var level=require("level");
var Level = require("level");
var nThen = require('nthen');
module.exports.create = function(conf,cb){
console.log("Loading leveldb");
var getIndex = function(db, cName, cb) {
db.get(cName+'=>index', function(e, out){
if (e) { throw e; }
cb(parseInt(out));
});
};
var db=level(conf.levelPath||'./test.level.db'),
indices={},
Channel={};
var insert = function (db, channelName, content, cb) {
var index;
nThen(function (waitFor) {
getIndex(db, channelName, waitFor(function (i) { index = i; }));
}).nThen(function (waitFor) {
db.put(channelName+'=>index', ''+index, waitFor(function (e) { if (e) { throw e; } }));
}).nThen(function (waitFor) {
db.put(channelName+'=>'+index, content, waitFor(function (e) { if (e) { throw e; } }));
}).nThen(cb);
};
var makeChannel=function(cName){
Channel[cName]={
lastModified:0,
messages:[],
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); }
}));
};
},
makeIndex=function(cName){
// initializing to negative one means we can increment on inserts
// so we always start from zero.
indices[cName]=-1;
},
loadIndex=function(cName, out){
indices[cName]=parseInt(out);
typeof indices[cName] !== 'number' &&
console.error("FOUND A NON-NUMERIC INDEX for channel: %s", cName);
},
getIndex=function(cName,f){
if(typeof indices[cName] !== 'undefined'){
f(indices[cName]);
}else{
// get and increment the channelIndex
db.get(cName+'=>index',function(e,out){
if(e){
// it doesn't exist, so initialize it
makeIndex(cName);
}else{
// it exists. parse it
loadIndex(cName,out);
}
f(indices[cName]);
again(0);
});
}
};
module.exports.create = function (conf, cb) {
var db = Level(conf.levelPath || './test.level.db');
cb({
message: function(cName,content,cb){
getIndex(cName,function(index){
var index = ++indices[cName];
db.put(cName+'=>index', ''+index,function(e){
if(e) console.error(e);
});
db.put(cName+'=>'+index, content, function(err){
if(err){
console.log(err);
}
cb();
});
});
message: function (channelName, content, cb) {
insert(db, channelName, content, cb);
},
getMessages: function(cName, cb){
/* get all messages relating to a channel */
getIndex(cName, function(index){
var last = index,
i = 0,
next = function () {
db.get(cName+'=>'+i, function (e,out) {
if(e) return console.error(e);
cb(out);
if (++i <= last) {
next();
getMessages: function (channelName, msgHandler) {
getMessages(db, channelName, msgHandler);
}
});
};
next();
});
},
});
};

Loading…
Cancel
Save