import { safeJsonParse , safeJsonStringify } from "@connext/utils" ; import localStorage from "localStorage" ; import { storeDefaults } from "../constants" ; import { KeyValueStorage } from "../types" ; export class WrappedLocalStorage implements KeyValueStorage { private localStorage : Storage = localStorage ; constructor ( private readonly prefix = storeDefaults . PREFIX , private readonly separator = storeDefaults . SEPARATOR ) { } init ( ) { return Promise . resolve ( ) ; } close ( ) { return Promise . resolve ( ) ; } async getItem < T > ( key ) { const item = this . localStorage . getItem ( `${ this . prefix }${ this . separator }${ key }` ) ; return safeJsonParse ( item ) ; } async setItem < T > ( key , value ) { this . localStorage . setItem ( `${ this . prefix }${ this . separator }${ key }` , safeJsonStringify ( value ) ) ; } async removeItem ( key ) { this . localStorage . removeItem ( `${ this . prefix }${ this . separator }${ key }` ) ; } async getKeys ( ) { const relevantKeys = Object . keys ( this . localStorage ) . filter ( ( key ) => key . startsWith ( this . prefix ) ) ; return relevantKeys . map ( ( key ) => key . split ( `${ this . prefix }${ this . separator }` ) [ 1 ] ) ; } async getEntries ( ) { return Object . entries ( this . localStorage ) . filter ( ( [ name , _ ] ) => name . startsWith ( this . prefix ) ) . map ( ( [ name , value ] ) => [ name . replace ( `${ this . prefix }${ this . separator }` , "" ) , safeJsonParse ( value ) , ] ) ; } getKey ( ... args ) { return args . join ( this . separator ) ; } } export default WrappedLocalStorage ;