rindexed.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. ;(function(){
  2. function Store(opt){
  3. opt = opt || {};
  4. opt.file = String(opt.file || 'radata');
  5. var db = null, u;
  6. try{opt.indexedDB = opt.indexedDB || indexedDB}catch(e){}
  7. try{if(!opt.indexedDB || 'file:' == location.protocol){
  8. var store = {}, s = {};
  9. store.put = function(f, d, cb){ s[f] = d; cb(null, 1) };
  10. store.get = function(f, cb){ cb(null, s[f] || u) };
  11. console.log('Warning: No indexedDB exists to persist data to!');
  12. return store;
  13. }}catch(e){}
  14. var store = function Store(){};
  15. if(Store[opt.file]){
  16. console.log("Warning: reusing same IndexedDB store and options as 1st.");
  17. return Store[opt.file];
  18. }
  19. Store[opt.file] = store;
  20. store.start = function(){
  21. var o = indexedDB.open(opt.file, 1);
  22. o.onupgradeneeded = function(eve){ (eve.target.result).createObjectStore(opt.file) }
  23. o.onsuccess = function(){ db = o.result }
  24. o.onerror = function(eve){ console.log(eve||1); }
  25. }; store.start();
  26. store.put = function(key, data, cb){
  27. if(!db){ setTimeout(function(){ store.put(key, data, cb) },1); return }
  28. var tx = db.transaction([opt.file], 'readwrite');
  29. var obj = tx.objectStore(opt.file);
  30. var req = obj.put(data, ''+key);
  31. req.onsuccess = obj.onsuccess = tx.onsuccess = function(){ cb(null, 1) }
  32. req.onabort = obj.onabort = tx.onabort = function(eve){ cb(eve||'put.tx.abort') }
  33. req.onerror = obj.onerror = tx.onerror = function(eve){ cb(eve||'put.tx.error') }
  34. }
  35. store.get = function(key, cb){
  36. if(!db){ setTimeout(function(){ store.get(key, cb) },9); return }
  37. var tx = db.transaction([opt.file], 'readonly');
  38. var obj = tx.objectStore(opt.file);
  39. var req = obj.get(''+key);
  40. req.onsuccess = function(){ cb(null, req.result) }
  41. req.onabort = function(eve){ cb(eve||4) }
  42. req.onerror = function(eve){ cb(eve||5) }
  43. }
  44. setInterval(function(){ db && db.close(); db = null; store.start() }, 1000 * 15); // reset webkit bug?
  45. return store;
  46. }
  47. if(typeof window !== "undefined"){
  48. (Store.window = window).RindexedDB = Store;
  49. } else {
  50. try{ module.exports = Store }catch(e){}
  51. }
  52. try{
  53. var Gun = Store.window.Gun || require('../gun');
  54. Gun.on('create', function(root){
  55. this.to.next(root);
  56. root.opt.store = root.opt.store || Store(root.opt);
  57. });
  58. }catch(e){}
  59. }());