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,13 +71,33 @@ 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 {
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 {
@ -88,10 +108,6 @@ Memory.prototype.loadFromFile = function(callback) {
}
callback && callback();
}
});
} else {
process.nextTick(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);