diff --git a/lib/connectors/memory.js b/lib/connectors/memory.js index 549bf6f2..7c337d43 100644 --- a/lib/connectors/memory.js +++ b/lib/connectors/memory.js @@ -54,6 +54,11 @@ Memory.prototype.loadFromFile = function(callback) { data = JSON.parse(data.toString()); self.ids = data.ids || {}; self.cache = data.models || {}; + } else { + if(!self.cache) { + self.ids = {}; + self.cache = {}; + } } callback && callback(); } @@ -80,13 +85,16 @@ Memory.prototype.saveToFile = function (result, callback) { }, null, ' '); fs.writeFile(self.settings.file, data, function (err) { - cb(err, result); - task && task(err, result); + cb(err); + task.callback && task.callback(err, task.data); }); }, 1); } // Enqueue the write - self.writeQueue.push(callback); + self.writeQueue.push({ + data: result, + callback: callback + }); } else { process.nextTick(function () { callback && callback(null, result); @@ -97,8 +105,10 @@ Memory.prototype.saveToFile = function (result, callback) { Memory.prototype.define = function defineModel(definition) { this.constructor.super_.prototype.define.apply(this, [].slice.call(arguments)); var m = definition.model.modelName; - this.cache[m] = {}; - this.ids[m] = 1; + if(!this.cache[m]) { + this.cache[m] = {}; + this.ids[m] = 1; + } }; Memory.prototype.create = function create(model, data, callback) { @@ -121,6 +131,9 @@ Memory.prototype.create = function create(model, data, callback) { var idName = this.idName(model); id = (props[idName] && props[idName].type && props[idName].type(id)) || id; this.setIdValue(model, data, id); + if(!this.cache[model]) { + this.cache[model] = {}; + } this.cache[model][id] = JSON.stringify(data); this.saveToFile(id, callback); }; diff --git a/test/memory.test.js b/test/memory.test.js index dcd8a163..4c613270 100644 --- a/test/memory.test.js +++ b/test/memory.test.js @@ -40,10 +40,10 @@ describe('Memory connector', function () { }); var count = 0; - var id = 1; + var ids = []; async.eachSeries(['John1', 'John2', 'John3'], function (item, cb) { User.create({name: item}, function (err, result) { - id = result.id; + ids.push(result.id); count++; readModels(function (err, json) { assert.equal(Object.keys(json.models.User).length, count); @@ -52,10 +52,17 @@ describe('Memory connector', function () { }); }, function (err, results) { // Now try to delete one - User.deleteById(id, function (err) { + User.deleteById(ids[0], function (err) { readModels(function (err, json) { assert.equal(Object.keys(json.models.User).length, 2); - done(); + User.upsert({id: ids[1], name: 'John'}, function(err, result) { + readModels(function (err, json) { + assert.equal(Object.keys(json.models.User).length, 2); + var user = JSON.parse(json.models.User[ids[1]]); + assert.equal(user.name, 'John'); + done(); + }); + }); }); }); });