Local Storage

This commit is contained in:
Ritchie Martori 2014-05-07 07:47:12 -07:00 committed by Ritchie Martori
parent 0866a55cb2
commit 6c91201f79
1 changed files with 42 additions and 13 deletions

View File

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