import { createSerializer , createDeserializer , SerializerFunction , DeserializerFunction , trySerialize , tryDeserialize , isNullOrUndefined } from '@src/shared/utils' ; import { ref , Ref } from '@src/api' ; export interface StorageOptions { isParsing : boolean ; serializer ? : SerializerFunction ; deserializer ? : DeserializerFunction ; } const defaultOptions = { isParsing : false } ; export function createStorage ( storage , key , options ? ) { const { isParsing , ... opts } = Object . assign ( { } , defaultOptions , options ) ; const serializer = createSerializer ( opts . serializer ) ; const deserializer = createDeserializer ( opts . deserializer ) ; const item = ref ( null ) ; const getItem = ( ) => { try { const itemVal = tryDeserialize ( storage . getItem ( key ) , deserializer , isParsing ) ; if ( ! isNullOrUndefined ( itemVal ) ) item . value = itemVal ; } catch ( error ) { } } ; const setItem = ( newVal ) => { try { const newItemVal = trySerialize ( newVal , serializer , isParsing ) ; storage . setItem ( key , newItemVal ) ; item . value = tryDeserialize ( newItemVal , deserializer , isParsing ) ; } catch ( error ) { } } ; const removeItem = ( ) => { try { storage . removeItem ( key ) ; item . value = null ; } catch ( error ) { item . value = null ; } } ; return { item , getItem , setItem , removeItem } ; }