SHARE
TWEET

JSON Local Storage (JLOS) with Phonegap file archive

salmanff Mar 9th, 2012 314 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* JLoS - JSON Local Stortage Micro-library Overview
  2.  
  3. At its simplest, JLoS just automates saving a variable content in local storage...
  4.  var examplevar = new jlos('examplevar')
  5.  From there, you can treat examplevar.data as a regular json object and read write it as you will....
  6.     DATA SHOULD ONLY BE PUT UNDER ".data"!!!!
  7.  
  8.  examplevar.save saves it to localStorage['examplevar']
  9.  
  10.  When a program is initialised, the dta is fetched from localStorage
  11.  
  12.  All that is very simple.
  13.  
  14.  If you don't need to "archive' the data in a text file, you can use jlos-simple http://pastebin.com/1SACKR1n.
  15.  
  16.  But you also have the option of using the file system to either 'archive' your object (ie in the file system), or use the options to autoarchive (archive automatically to file system when save is called, or just use 'filesysonly'...
  17.  
  18.  
  19. */
  20. /* Options...
  21. Currently, options are:
  22.         - 'autoarchive': Saves to file system when save() is called
  23.         - 'filesysonly': Doesn't use localstorage - just uses file system
  24.         - 'getdatafromfile': Upon initialisation, it gets the data from the file system. It is upto the progam to make sure that the data gets archived after any changes.
  25. Options under consideration:
  26.         - KeepChangelog - log all changes to the items
  27.         - imposeSchema - impose rules on JSON schema
  28.  
  29. Additional methods under consideration - more JSON related than jlos related:
  30.         - query(expressionlist, path)
  31.         - JSON viewer
  32.  
  33. Archiving functionality is now specific to Phonegap but can be adapted to other systems quite easily -
  34. To use the local file system... there has to be a Directory Entry jlosDir initiated. You can call  getAppPath, use you rown function to set jlosDir.
  35.  
  36. */
  37. /*
  38. Note - This micro-library is in severe need of exception handling. ;) May come with demand!!
  39. Alo note: THis has not been production tested...
  40. */
  41.  
  42. var jlosDir; // directory object for where jlos files are stored - can be created with getAppPath
  43. var ioQueue = {'initdir':{'file':''}, 'readqueue':[], 'status':''};
  44. // List Queue of things that need to be done using the filessystem
  45. var doOnJlosInit = null;
  46.  
  47. function jlos(name, options) {
  48.   this.name = name;
  49.   this.initialize(options);
  50. }
  51.  
  52. jlos.prototype.initialize = function (options) {
  53.  this.meta = options? options : {};
  54.  if (localStorage["jlos-data-"+this.name] && !options.getdatafromfile) {
  55.         this.data = JSON.parse(unescape(localStorage["jlos-data-"+this.name]));
  56.  } else if (options.autoarchive || options.getdatafromfile || options.filesysonly) {
  57.         this.data = {}; //
  58.         ioQueue['readqueue'].push({'name': this.name})
  59.         if (jlosDir && ioQueue['status']!='inProcess') {manageioQueue();} // start manageioQueue process, unless it is ialready running (ie if its status is inProcess) - that is, it is in the middle of initializing
  60.  } else {
  61.         this.data = {};
  62.  }
  63. };
  64.  
  65. jlos.prototype.save = function () {
  66.  if (!this.meta.filesysonly) {
  67.         localStorage["jlos-data-"+this.name]= escape(JSON.stringify(this.data));
  68.  }
  69.  if (this.meta.filesysonly || this.meta.autoarchive) {
  70.         this.archive();
  71.  }
  72. };
  73.  
  74. jlos.prototype.remove = function () {
  75.  this.data=null;
  76.  if (localStorage["jlos-data-"+this.name]) {
  77.         localStorage.removeItem("jlos-data-"+this.name);
  78.  }
  79.  if (jlosDir) {
  80.         jlosDir.getFile("jlos-data-"+this.name+".txt", {create: false}, jlosGotFileForDelete, null);
  81.  }
  82. };
  83.  
  84. jlos.prototype.archive = function () {
  85.         console.log('going to Archive '+this.name+' in the file system');
  86.         jlosDir.getFile("jlos-data-"+this.name+".txt", {create: true}, jlosGotFileforReWrite, jlosFailgetFileForReWrite);
  87. };
  88.  
  89. function jlosGotFileforReWrite(fileEntry){
  90.         fileEntry.createWriter(jlosGotFileWriter, jlosFailgetFileForReWrite);
  91. }
  92. function jlosGotFileWriter(writer){
  93.                 writer.onwrite = function(evt) {
  94.             console.log("write success");
  95.         };
  96.                 var varname = writer.fileName.split('jlos-data-')[1].slice(0,-4)
  97.                 console.log('writing content: '+JSON.stringify(window[varname].data));
  98.                 var formattedContent = escape(JSON.stringify(window[varname].data));
  99.         writer.write(formattedContent);
  100.                 //writer.truncate(formattedContent.length);
  101. }
  102. function jlosFailgetFileForReWrite(evt){
  103.         alert('error writing to ile system.');
  104.         console.log(evt.target.error.code);
  105. }
  106.  
  107. var getAppPath = function(AppName) {
  108.         ioQueue['status']='inProcess';
  109.         ioQueue['initdir'] = {'file':AppName}; // this is always called at the beginning so it is already empty
  110.         window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, jlosOnInitalFileSysemSuccess, jlosFilesystemfail);
  111. };
  112. function jlosOnInitalFileSysemSuccess(fileSystem) {
  113.         var dirname = ioQueue['initdir'].file;
  114.         fileSystem.root.getDirectory(dirname, {create: true, exclusive: false}, jlosGotDirectorySuccess, jlosFilesystemfail2);
  115. }
  116. function jlosFilesystemfail() {
  117.         alert('Error nitializing the local file system.');
  118. }
  119. function jlosFilesystemfail2(e) {
  120.         alert('Error nitializing the local file system 2.'+e);
  121. }
  122. function jlosGotDirectorySuccess(DirEnt) {
  123.         jlosDir = DirEnt;
  124.         manageioQueue();
  125. }
  126. function manageioQueue() {
  127.         ioQueue['status']='inProcess';
  128.         if(ioQueue['readqueue'].length > 0 && jlosDir) {
  129.                 ioQueue['readqueue'][0].status='loading';
  130.                 jlosDir.getFile("jlos-data-"+ioQueue['readqueue'][0].name+".txt", {create: true}, jlosGotFileEntry, jlosFailFileEntry);
  131.         } else {
  132.                 ioQueue['status']='';
  133.                 if (doOnJlosInit) {doOnJlosInit();}
  134.         }
  135. }
  136. function jlosFailFileEntry(evt) {
  137.         console.log('error reading files');
  138.         console.log(evt.target.error.code);
  139.         ioQueue['readqueue'] = ioQueue['readqueue'].length==1? [] : ioQueue['readqueue'].slice(1);
  140.         manageioQueue();
  141. }
  142. function jlosGotFileEntry(file) {
  143.         var datareader = new FileReader();
  144.         datareader.onloadend = function(evt) {
  145.                 varname = file.name.slice(10,-4);
  146.                 console.log('Read from file system '+varname+ ' from path '+file.name);
  147.                 //console.log('read file content '+evt.target.result)
  148.                 if (evt.target.result.length > 0) {
  149.                         window[varname].data = JSON.parse(unescape(evt.target.result));
  150.                 } else {
  151.                         window[varname].data = {}
  152.                 }
  153.                 //console.log('var '+varname+':'+window[varname].data);
  154.                 ioQueue['readqueue'] = ioQueue['readqueue'].length==1? [] : ioQueue['readqueue'].slice(1);
  155.                 manageioQueue();
  156.         }
  157.         datareader.readAsText(file);   
  158.         console.log('Reading '+"jlos-data-"+ioQueue['readqueue'][0].name+".txt");
  159. }
  160.  
  161. function jlosGotFileForDelete(file) {
  162.         file.remove();
  163. }
RAW Paste Data
Top