rindexed.js 2.4 KB

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