Local Storage

This commit is contained in:
Ritchie Martori 2014-05-07 07:47:12 -07:00
parent 4049f7338e
commit cbf99d57a9
1 changed files with 42 additions and 13 deletions

View File

@ -71,27 +71,43 @@ function deserialize(dbObj) {
Memory.prototype.loadFromFile = function(callback) {
var self = this;
var hasLocalStorage = typeof window !== 'undefined' && window.localStorage;
var localStorage = hasLocalStorage && this.settings.localStorage;
if (self.settings.file) {
fs.readFile(self.settings.file, {encoding: 'utf8', flag: 'r'}, function (err, data) {
if (err && err.code !== 'ENOENT') {
callback && callback(err);
} else {
if (data) {
data = JSON.parse(data.toString());
self.ids = data.ids || {};
self.cache = data.models || {};
} else {
if(!self.cache) {
self.ids = {};
self.cache = {};
}
}
callback && callback();
parseAndLoad(data);
}
});
} else if(localStorage) {
var data = window.localStorage.getItem(localStorage);
data = data || '{}';
parseAndLoad(data);
} else {
process.nextTick(callback);
}
function parseAndLoad(data) {
if (data) {
try {
data = JSON.parse(data.toString());
} catch(e) {
return callback(e);
}
self.ids = data.ids || {};
self.cache = data.models || {};
} else {
if(!self.cache) {
self.ids = {};
self.cache = {};
}
}
callback && callback();
}
};
/*!
@ -100,7 +116,10 @@ Memory.prototype.loadFromFile = function(callback) {
*/
Memory.prototype.saveToFile = function (result, callback) {
var self = this;
if (this.settings.file) {
var file = this.settings.file;
var hasLocalStorage = typeof window !== 'undefined' && window.localStorage;
var localStorage = hasLocalStorage && this.settings.localStorage;
if (file) {
if(!self.writeQueue) {
// Create a queue for writes
self.writeQueue = async.queue(function (task, cb) {
@ -121,6 +140,16 @@ Memory.prototype.saveToFile = function (result, callback) {
data: result,
callback: callback
});
} else if (localStorage) {
// Flush out the models/ids
var data = JSON.stringify({
ids: self.ids,
models: self.cache
}, null, ' ');
window.localStorage.setItem(localStorage, data);
process.nextTick(function () {
callback && callback(null, result);
});
} else {
process.nextTick(function () {
callback && callback(null, result);
@ -421,4 +450,4 @@ function merge(base, update) {
base[key] = update[key];
});
return base;
}
}