diff --git a/lib/connectors/memory.js b/lib/connectors/memory.js index 1184ac44..0db0dc32 100644 --- a/lib/connectors/memory.js +++ b/lib/connectors/memory.js @@ -51,6 +51,24 @@ Memory.prototype.connect = function (callback) { } }; +function serialize(obj) { + if(obj === null || obj === undefined) { + return obj; + } + return JSON.stringify(obj); +} + +function deserialize(dbObj) { + if(dbObj === null || dbObj === undefined) { + return dbObj; + } + if(typeof dbObj === 'string') { + return JSON.parse(dbObj); + } else { + return dbObj; + } +} + Memory.prototype.loadFromFile = function(callback) { var self = this; if (self.settings.file) { @@ -142,7 +160,7 @@ Memory.prototype.create = function create(model, data, callback) { if(!this.cache[model]) { this.cache[model] = {}; } - this.cache[model][id] = JSON.stringify(data); + this.cache[model][id] = serialize(data); this.saveToFile(id, callback); }; @@ -161,7 +179,7 @@ Memory.prototype.updateOrCreate = function (model, data, callback) { }; Memory.prototype.save = function save(model, data, callback) { - this.cache[model][this.getIdValue(model, data)] = JSON.stringify(data); + this.cache[model][this.getIdValue(model, data)] = serialize(data); this.saveToFile(data, callback); }; @@ -185,7 +203,7 @@ Memory.prototype.destroy = function destroy(model, id, callback) { Memory.prototype.fromDb = function (model, data) { if (!data) return null; - data = JSON.parse(data); + data = deserialize(data); var props = this._models[model].properties; for (var key in data) { var val = data[key]; @@ -374,8 +392,8 @@ Memory.prototype.updateAttributes = function updateAttributes(model, id, data, c this.setIdValue(model, data, id); var cachedModels = this.cache[model]; - var modelAsString = cachedModels && this.cache[model][id]; - var modelData = modelAsString && JSON.parse(modelAsString); + var modelData = cachedModels && this.cache[model][id]; + modelData = modelData && deserialize(modelData); if (modelData) { this.save(model, merge(modelData, data), cb);