diff --git a/lib/store.js b/lib/store.js index dc0d839..36139e6 100644 --- a/lib/store.js +++ b/lib/store.js @@ -11,8 +11,6 @@ function Store(opts, cb) { if (!(this instanceof Store)) return new Store(opts, cb); if (cb === undefined) cb = function () {}; var self = this; - var actionQueue = []; - var ready = false; if (typeof opts === 'string') { var opts = { @@ -33,14 +31,20 @@ function Store(opts, cb) { opts.json = opts.json || false; + var actionQueue = []; + var ready = false; self.on('ready', function () { ready = true; actionQueue.forEach(function (action) { - self[action.action].apply(self, action.args); + action.action.apply(self, action.args); }); delete actionQueue; }); + function queue(action, args) { + actionQueue.push({ action : action, args : [].slice.call(args) }); + } + function initStoreTable() { var hadRow = false; db.query( @@ -78,13 +82,9 @@ function Store(opts, cb) { ); } - function queue(action, args) { - actionQueue.push({ action : action, args : [].slice.call(args) }); - } - self.set = function (key, value, cb) { if (!ready) { - queue('set', arguments); + queue(self.set, arguments); return; } if (cb === undefined) cb = function () {} @@ -105,7 +105,7 @@ function Store(opts, cb) { self.get = function (key, cb) { if (!ready) { - queue('get', arguments); + queue(self.get, arguments); return; } if (cb === undefined) cb = function () {} @@ -132,7 +132,7 @@ function Store(opts, cb) { self.remove = function (key, cb) { if (!ready) { - queue('remove', arguments); + queue(self.remove, arguments); return; } if (cb === undefined) cb = function () {}; @@ -155,7 +155,7 @@ function Store(opts, cb) { self.length = function (cb) { if (!ready) { - queue('length', arguments); + queue(self.length, arguments); return; } if (cb === undefined) cb = function () {}; @@ -180,14 +180,14 @@ function Store(opts, cb) { } }); - self.stream = function () { + self.stream = function (emitter) { + if (!emitter) emitter = new EventEmitter; + if (!ready) { - queue('stream', arguments); - return; + queue(self.stream.bind(self,emitter), arguments); + return emitter; } - var emitter = new EventEmitter; - db.query( "SELECT * FROM store", function (error, row) { @@ -212,7 +212,7 @@ function Store(opts, cb) { self.all = function (cb) { if (!ready) { - queue('all', arguments); + queue(self.all, arguments); return; } var keys = [];