Uno-Dan

DBMagic with update method.

Feb 27th, 2021
1,068
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. const log = console.log;
  3.  
  4. class Table {
  5.   constructor( db, name, debug=false) {
  6.     this.db = db;
  7.     this.dbName = db.db;
  8.     this.store = name;
  9.     this.debug = debug;
  10.    
  11.     this.indexedDB = window.indexedDB || window.mozIndexedDB ||
  12.     window.webkitIndexedDB || window.msIndexedDB;
  13.    
  14.     return this.table( name );
  15.   }
  16.  
  17.   table( store ) {
  18.     let stores = this.db.stores;
  19.    
  20.     const do_upgrade = () => {
  21.       stores.push( store );
  22.      
  23.       return new Promise( ( resolve, reject ) => {
  24.        
  25.         let req = this.indexedDB.open( this.dbName, stores.length + 1 );
  26.        
  27.         req.onerror = e => reject( e );
  28.         req.onsuccess = () => {
  29.           this.db.stores.push( store );
  30.           req.result.close();
  31.           resolve( this );
  32.         };
  33.         req.onupgradeneeded = () => req.result
  34.         .createObjectStore( store, { keyPath: 'id' } );
  35.       } );
  36.     };
  37.    
  38.     return new Promise( ( resolve, reject ) => {
  39.      let openReq = this.indexedDB.open( this.dbName );
  40.      
  41.       openReq.onerror = () => {
  42.         do_upgrade();
  43.         resolve( this );
  44.       };
  45.      
  46.       openReq.onsuccess = () => {
  47.         openReq.result.close();
  48.         if ( ! stores.includes( store ) ) {
  49.           do_upgrade();
  50.         }
  51.         resolve( this );
  52.       };
  53.     } );  
  54.   }
  55.  
  56.   add_que( args ) {
  57.     return new Promise(( resolve, reject ) => {
  58.       let openReq = this.indexedDB.open( this.dbName );
  59.  
  60.       openReq.onerror = e => reject( e );
  61.  
  62.       openReq.onsuccess = () => {
  63.         let tx = openReq.result.transaction ( [ this.store ], 'readwrite' );
  64.         let addReq = tx.objectStore( this.store ).add( args );
  65.         tx.commit();
  66.  
  67.         addReq.onerror = e => {
  68.           if ( this.debug )
  69.             log( `[ ERROR:add ], could not add key [${ args.id }] in store [${
  70.             addReq.source.name }] in database [${ this.dbName }]` );
  71.           reject( e );  
  72.         };
  73.  
  74.         addReq.onsuccess = () => {  
  75.           if ( this.debug )
  76.             log( `[ INFO:add ], Added key [${ args.id }] in store [${
  77.             addReq.source.name }] in database [${ this.dbName }]` );
  78.           resolve( this );  
  79.           openReq.result.close();
  80.         };
  81.       };
  82.     } );
  83.   }
  84.  
  85.   async add( args ) {
  86.     if ( ! Array.isArray( args ) ) args = [ args ];
  87.     let promises = [];
  88.     args.forEach( item => { promises.push( this.add_que( item ) ); } );
  89.     await promises;
  90.     return this;
  91.   }
  92.  
  93.   update( args ) {
  94.     return this.get( { id: args.id } ).then( values => {
  95.       args = Object.assign({}, values, args );
  96.      
  97.       return new Promise(( resolve, reject ) => {
  98.         let openReq = this.indexedDB.open( this.dbName );
  99.  
  100.         openReq.onerror = e => reject( e );
  101.  
  102.         openReq.onsuccess = () => {
  103.           let tx = openReq.result.transaction ( [ this.store ], 'readwrite' );
  104.           let addReq = tx.objectStore( this.store ).put( args );
  105.           tx.commit();
  106.  
  107.           addReq.onerror = e => {
  108.             if ( this.debug )
  109.               log( `[ ERROR:add ], could not update key [${ args.id }] in store [${
  110.               addReq.source.name }] in database [${ this.dbName }]` );
  111.             reject( e );  
  112.           };
  113.  
  114.           addReq.onsuccess = () => {  
  115.             if ( this.debug )
  116.               log( `[ INFO:update ], Updated key [${ args.id }] in store [${
  117.               addReq.source.name }] in database [${ this.dbName }]` );
  118.             resolve( this );  
  119.             openReq.result.close();
  120.           };
  121.         };
  122.       } );
  123.     } );
  124.   }
  125.          
  126.   get( args ) {
  127.     let store = this.store;
  128.     let dbName = this.dbName;
  129.    
  130.     return new Promise( ( resolve, reject ) => {
  131.       var openReq = this.indexedDB.open( dbName );
  132.  
  133.         openReq.onerror = e => reject( e );
  134.  
  135.         openReq.onsuccess = () => {
  136.           let tx = openReq.result.transaction ( [ store ], 'readonly' );
  137.        
  138.           let obj = tx.objectStore( store );
  139.           let req = args ? obj.get( args.id ) : obj.getAll();
  140.           req.onerror = e => {
  141.             if ( this.debug )
  142.               log( `[ ERROR:getAll ], could not retrieve keys from store [${
  143.               req.source.name }] in database [${ dbName }]` );
  144.             reject( e );  
  145.           };
  146.  
  147.           req.onsuccess = () => {
  148.             if ( this.debug )
  149.               log( `[ INFO:getAll ], Retrieved all keys from store [${
  150.               req.source.name }] in database [${ dbName }]` );
  151.             resolve( req.result );  
  152.             openReq.result.close();
  153.           };
  154.         };
  155.     } );
  156.   }
  157.  
  158. }
  159.  
  160. class DB {
  161.   constructor( name, debug=false) {
  162.     this.db = name;
  163.     this.debug = debug;
  164.     this.stores = [];
  165.     this.upgrade = false;
  166.     this.init();
  167.   }
  168.  
  169.   init() {
  170.     let indexedDB = window.indexedDB || window.mozIndexedDB ||
  171.     window.webkitIndexedDB || window.msIndexedDB;
  172.    
  173.     return new Promise( ( resolve, reject ) => {
  174.       let req = indexedDB.open( this.db );
  175.      
  176.       req.onerror = e => reject( e );
  177.       req.onsuccess = () => { req.result.close(); resolve(); };
  178.       req.onupgradeneeded = () => { return true; };
  179.     } );
  180.   }
  181.  
  182.   table( name ) {
  183.     let tbl = new Table( this, name, this.debug );
  184.    
  185.     return tbl;
  186.   }
  187. }
  188.  
  189.  
  190.  
  191. jQuery( document ).ready( () => {
  192.   $( '#testDB' ).on( 'click', function() {
  193.      
  194.     $( 'body' ).append( $( '<div></br>Creating the databases.</div>' ) );
  195.     let db1 = new DB( 'MyDB1', true );
  196.     const setup = async () => {
  197.         let tbl = await db1.table( 'users' );
  198.         await tbl.add( { id: 1, fName: 'Joe', lName: 'Doe', group: 3 } );
  199.         await tbl.add( [
  200.         { id: 2, fName: 'Jane', lName: 'Doe', group: 1 },
  201.         { id: 3, fName: 'Peter', lName: 'Parker', group: 2 }
  202.         ] );
  203.        
  204.         log('Test 1 Read data:', await tbl.get() );
  205.         await tbl.update( { id: 2, fName: 'Mary', lName: 'Smith', group: 3 } );
  206.         log('Test 1 Updated data:', await tbl.get() );
  207.        
  208.     };
  209.     setup();
  210.  
  211.     let db2 = new DB( 'MyDB2', true );
  212.     db2.table( 'users' )
  213.     .then( tbl => {
  214.         return tbl.add( [
  215.         { id:1, fName: 'Joe', lName: 'Smith', group: 2 },
  216.         { id:2, fName: 'Jane', lName: 'Smith', group: 3 }
  217.         ] );    
  218.     } )
  219.     .then( tbl => { return tbl.get(); } )
  220.    
  221.     .then( results => {
  222.         log('Results:', results );
  223.             $( 'body' ).append( $( '<div></br>Databases created, check the console now.</div>' ) );
  224.         } );
  225.     } );  
  226. } );  
  227.  
  228.  
  229.  
  230.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×