import { Try , Success } from '@/utils/fp/Try' ; import { FetchError } from '@/utils/fetch' ; import { getLocalStorage , setLocalStorage } from '@/utils/storage' ; type Service < T > = ( ) => Promise < Try < T , FetchError > > ; param service param name param expireIn export function cacheService < T extends object | string > ( service , name , expireIn = 0 ) { const key = `cache-${ name }` ; let cache = getLocalStorage ( key ) as T | null ; let isFetching = false ; let promise ; return ( ) => { if ( cache ) { return Promise . resolve ( Try . of < T , FetchError > ( Success . of ( cache ) ) ) ; } if ( isFetching ) { return promise ; } isFetching = true ; promise = service ( ) ; return promise . then ( res => { isFetching = false ; res . fail ( ) . succeed ( value => { cache = value ; setLocalStorage ( key , value , expireIn ) ; } ) ; return res ; } ) ; } ; }