import { RecordState } from 'src/RecordState' ; import { ITable } from './TableBuilder' ; export class Database < T extends RecordState > { private readonly indexDb : IDBFactory ; private database : IDBDatabase | null = null ; private readonly table : ITable ; constructor ( table ) { this . indexDb = window . indexedDB ; this . table = table ; this . OpenDatabase ( ) ; } public Create ( state ) { const dbStore = this . GetObjectStore ( ) ; dbStore ! . add ( state ) ; } public Read ( ) { return new Promise ( ( response ) => { const dbStore = this . GetObjectStore ( ) ; const items = new Array < T > ( ) ; const request = dbStore ! . openCursor ( ) ; request . onsuccess = ( e ) => { const cursor = e . target . result ; if ( cursor ) { const result = cursor . value ; if ( result . IsActive ) { items . push ( result ) ; } cursor . continue ( ) ; } else { response ( items ) ; } } ; } ) ; } public Update ( state ) { return new Promise ( ( resolve ) => { const dbStore = this . GetObjectStore ( ) ; const innerRequest = dbStore ! . put ( state ) ; innerRequest . onsuccess = ( ) => { resolve ( ) ; } ; } ) ; } public Delete ( idx ) { return new Promise ( ( resolve ) => { const dbStore = this . GetObjectStore ( ) ; const innerRequest = dbStore ! . delete ( idx . toString ( ) ) ; innerRequest . onsuccess = ( ) => { resolve ( ) ; } ; } ) ; } private OpenDatabase ( ) { const open = this . indexDb . open ( this . table . Database ( ) , this . table . Version ( ) ) ; open . onupgradeneeded = ( e ) => { this . UpgradeDatabase ( e . target . result ) ; } ; open . onsuccess = ( e ) => { this . database = e . target . result ; } ; } private UpgradeDatabase ( database ) { this . database = database ; this . table . Build ( this . database ) ; } private GetObjectStore ( ) { try { const transaction = this . database ! . transaction ( this . table . TableName ( ) , "readwrite" ) ; const dbStore = transaction . objectStore ( this . table . TableName ( ) ) ; return dbStore ; } catch ( Error ) { return null ; } } }