import { Injectable } from 'angular-ts-decorators' ; import autobind from 'autobind-decorator' ; import { clear , createStore , del , get , keys as idbKeys , set , UseStore } from 'idb-keyval' ; import { StoreKey } from '../../../shared/store/store.enum' ; import { StoreContent , TraceLogItem } from '../../../shared/store/store.interface' ; import { StoreService } from '../../../shared/store/store.service' ; @ autobind @ Injectable ( 'StoreService' ) export class WebExtStoreService extends StoreService { dbName = 'xbs-store' ; store : UseStore ; storeName = 'xbs' ; static $inject = [ '$q' ] ; constructor ( $q ) { super ( $q ) ; this . store = createStore ( this . dbName , this . storeName ) ; } protected addTraceLog ( newLogItem ) { return this . getAllTraceLogs ( ) . then ( ( traceLogItems = [ ] ) => { traceLogItems . push ( newLogItem ) ; return this . setInIdbKeyval ( StoreKey . TraceLog , traceLogItems ) ; } ) ; } protected clear ( ) { return clear ( this . getStore ( ) ) ; } protected getFromStore < T = StoreContent > ( keys = [ ] ) { const values = new Array ( keys . length ) ; return this . $q < T [ ] > ( ( resolve , reject ) => { const keysWithoutTraceLog = keys . filter ( ( key ) => key !== StoreKey . TraceLog ) ; if ( keysWithoutTraceLog . length === 0 ) { return resolve ( ) ; } return this . $q . all ( keysWithoutTraceLog . map ( ( key ) => get < any > ( key , this . getStore ( ) ) ) ) . then ( ( results ) => { keysWithoutTraceLog . forEach ( ( key , index ) => { values [ keys . indexOf ( key ) ] = results [ index ] ; } ) ; resolve ( ) ; } ) ; } ) . then ( ( ) => { if ( ! keys . includes ( StoreKey . TraceLog ) ) { return ; } return this . getAllTraceLogs ( ) . then ( ( traceLogItems ) => { values [ keys . indexOf ( StoreKey . TraceLog ) ] = traceLogItems ; } ) ; } ) . then ( ( ) => values ) ; } protected getAllTraceLogs ( ) { return get < TraceLogItem [ ] > ( StoreKey . TraceLog , this . getStore ( ) ) . then ( ( traceLogItems ) => traceLogItems ) ; } protected getStore ( ) { return this . store ; } protected keys ( ) { return this . $q . resolve ( ) . then ( ( ) => idbKeys ( this . getStore ( ) ) ) ; } protected removeFromStore ( keys = [ ] ) { return this . $q . all ( keys . map ( ( key ) => del ( key , this . getStore ( ) ) ) ) . then ( ( ) => { } ) ; } protected setInStore ( key , value ) { if ( key === StoreKey . TraceLog ) { return this . addTraceLog ( value ) ; } return this . setInIdbKeyval ( key , value ) ; } protected setInIdbKeyval ( key , value ) { return set ( key , value , this . getStore ( ) ) ; } }