Refactor the serialize/deserialize into two functions

This commit is contained in:
Raymond Feng 2014-03-11 15:37:28 -07:00
parent aa11aad298
commit bef90bd529
1 changed files with 23 additions and 5 deletions

View File

@ -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) { Memory.prototype.loadFromFile = function(callback) {
var self = this; var self = this;
if (self.settings.file) { if (self.settings.file) {
@ -142,7 +160,7 @@ Memory.prototype.create = function create(model, data, callback) {
if(!this.cache[model]) { if(!this.cache[model]) {
this.cache[model] = {}; this.cache[model] = {};
} }
this.cache[model][id] = JSON.stringify(data); this.cache[model][id] = serialize(data);
this.saveToFile(id, callback); this.saveToFile(id, callback);
}; };
@ -161,7 +179,7 @@ Memory.prototype.updateOrCreate = function (model, data, callback) {
}; };
Memory.prototype.save = function save(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); this.saveToFile(data, callback);
}; };
@ -185,7 +203,7 @@ Memory.prototype.destroy = function destroy(model, id, callback) {
Memory.prototype.fromDb = function (model, data) { Memory.prototype.fromDb = function (model, data) {
if (!data) return null; if (!data) return null;
data = JSON.parse(data); data = deserialize(data);
var props = this._models[model].properties; var props = this._models[model].properties;
for (var key in data) { for (var key in data) {
var val = data[key]; var val = data[key];
@ -374,8 +392,8 @@ Memory.prototype.updateAttributes = function updateAttributes(model, id, data, c
this.setIdValue(model, data, id); this.setIdValue(model, data, id);
var cachedModels = this.cache[model]; var cachedModels = this.cache[model];
var modelAsString = cachedModels && this.cache[model][id]; var modelData = cachedModels && this.cache[model][id];
var modelData = modelAsString && JSON.parse(modelAsString); modelData = modelData && deserialize(modelData);
if (modelData) { if (modelData) {
this.save(model, merge(modelData, data), cb); this.save(model, merge(modelData, data), cb);