From 02659021d3960ea08049709c7e8294e0c74d8dc0 Mon Sep 17 00:00:00 2001 From: Manuel Araoz Date: Mon, 1 Sep 2014 18:42:52 -0300 Subject: [PATCH] cleaner plugin: removeUpTo --- lib/MessageDb.js | 41 +++++++++++++++++++++++++++++++++-------- test/test.MessageDb.js | 17 +++++++++++++++-- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/lib/MessageDb.js b/lib/MessageDb.js index 832087ce..ce6be5b1 100644 --- a/lib/MessageDb.js +++ b/lib/MessageDb.js @@ -86,7 +86,7 @@ MessageDb.prototype.authenticate = function(m) { MessageDb.parseKey = function(key) { var ret = {}; var spl = key.split('-'); - + ret.to = spl[1]; ret.ts = +spl[2]; @@ -124,14 +124,39 @@ MessageDb.prototype.getMessages = function(to, lower_ts, upper_ts, cb) { }); }; -MessageDb.prototype.removeUpTo = function(ts) { - preconditions.checkArgument(ts); - preconditions.checkArgument(typeof ts === 'number'); - var opts = {}; - db.createKeyStream(opts) - .on('data', function(key) { - console.log('key=', key) +MessageDb.prototype.getAll = function(cb) { + var list = []; + db.createReadStream() + .on('data', function(data) { + list.push(MessageDb.fromStorage(data)); + }) + .on('end', function() { + return cb(null, list); }); }; +MessageDb.prototype.removeUpTo = function(ts, cb) { + preconditions.checkArgument(ts); + preconditions.checkArgument(typeof ts === 'number'); + var opts = {}; + var dels = []; + db.createKeyStream(opts) + .on('data', function(key) { + var parsed = MessageDb.parseKey(key); + if (parsed.ts < ts) { + dels.push({ + type: 'del', + key: key + }); + } + }) + .on('end', function() { + db.batch(dels, function(err) { + if (err) return cb(err); + else cb(null, dels.length); + }) + }); + +}; + module.exports = soop(MessageDb); diff --git a/test/test.MessageDb.js b/test/test.MessageDb.js index 492c4547..960fc849 100644 --- a/test/test.MessageDb.js +++ b/test/test.MessageDb.js @@ -108,9 +108,22 @@ describe('MessageDb', function() { done(); }); }); - it('should be able #removeUpTo', function() { + it('should be able #removeUpTo', function(done) { var mdb = sharedMDB; - mdb.removeUpTo(microtime.now()); + var upper_ts = microtime.now(); + mdb.addMessage(message, function(err) { + expect(err).to.not.exist; + mdb.removeUpTo(upper_ts, function(err, n) { + expect(err).to.not.exist; + n.should.equal(4); + mdb.getAll(function(error, all) { + expect(error).to.not.exist; + all.length.should.equal(1); + done(); + }); + + }); + }); }); it('should be able to close instance', function() { var mdb = new MessageDb(opts);