import { parseJSON } from './util' ; import { driverType } from "./interfaces" ; export default class WebStorage { public readonly storage : Storage ; constructor ( public readonly prefix = 'app_' , driver = 'local' ) { this . storage = this . resolveDriver ( driver ) ; } prefixKey ( key ) { return this . prefix + String ( key ) ; } set ( key , value ) { return this . storage . setItem ( this . prefixKey ( key ) , JSON . stringify ( value ) ) ; } get < T extends any > ( key , defaultValue = null ) { let storedValue = null ; const item = this . storage . getItem ( this . prefixKey ( key ) ) ; if ( ! ! item ) { storedValue = parseJSON ( item ) ; } return storedValue === null ? defaultValue : storedValue ; } remove ( key ) { return this . storage . removeItem ( this . prefixKey ( key ) ) ; } clear ( force = false ) { if ( force ) { this . storage . clear ( ) ; } else { this . keys ( true ) . map ( ( key ) => { this . storage . removeItem ( key ) ; } ) ; } } keys ( withPrefix = false ) { const keys = [ ] ; Object . keys ( this . storage ) . forEach ( ( keyName ) => { if ( keyName . substr ( 0 , this . prefix . length ) === this . prefix ) { keys . push ( withPrefix ? keyName : keyName . substring ( this . prefix . length ) ) ; } } ) ; return keys ; } hasKey ( key ) { return this . keys ( ) . indexOf ( key ) !== - 1 ; } length ( ) { return this . keys ( ) . length ; } private resolveDriver ( driver ) { switch ( driver ) { case 'local' : return window . localStorage ; case 'session' : return window . sessionStorage ; default : throw new Error ( `Unknown driver supplied: ${ driver }` ) ; } } }