From cbf99d57a9f716e2b175b94533b127b8cc250a5c Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Wed, 7 May 2014 07:47:12 -0700 Subject: [PATCH] Local Storage --- lib/connectors/memory.js | 55 ++++++++++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 13 deletions(-) diff --git a/lib/connectors/memory.js b/lib/connectors/memory.js index 0db0dc32..90259e97 100644 --- a/lib/connectors/memory.js +++ b/lib/connectors/memory.js @@ -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; -} \ No newline at end of file +}