import { getStorage } from '@shared/manager/storage' ; import _isNil from 'lodash/isNil' ; export enum CachePolicy { /**
     * 存储在内存中
     */ Temporary , /**
     * 存储在rnStorage中
     * 过期时间为rnStorage的过期时间
     * NOTE: 在使用持久化存储时必须自行实现hash
     * 可以基于buildCacheHashPrefix来快速实现
     */ Persistent } /**
 * 序列化参数
 */ function stringifyArgs ( arg ) { switch ( typeof arg ) { case 'string' : return arg ; case 'number' : return String ( arg ) ; default : return JSON . stringify ( arg ) ; } } /**
 * 拼接参数
 */ function joinArgs ( args ) { return args . map ( stringifyArgs ) . join ( '$' ) ; } function defaultHash ( ... args ) { return `cache:factory$${ joinArgs ( args ) }` ; } param prefix export function buildCacheHashFnPrefix ( prefix ) { return ( ... args ) => `cache:factory$${ prefix }:${ joinArgs ( args ) }` ; } export function buildCacheFactory < T > ( policy , fn , hashFn = defaultHash ) { let cacheManager ; if ( policy === CachePolicy . Temporary ) { cacheManager = new TemporaryCache ( ) ; } else if ( policy === CachePolicy . Persistent ) { cacheManager = new PersistentCache ( ) ; } return async ( ... args ) => { const hash = hashFn ( ... args ) ; const cache = await cacheManager . get ( hash ) ; if ( ! _isNil ( cache ) ) { return cache ; } const ret = await fn ( ... args ) ; await cacheManager . set ( hash , ret ) ; return ret ; } ; } interface CacheManager { get ( hash ) : Promise < any > ; set ( hash , value ) : Promise < void > ; } class TemporaryCache implements CacheManager { temporaryCacheMap = { } ; async get ( hash ) { return this . temporaryCacheMap [ hash ] ; } async set ( hash , value ) { this . temporaryCacheMap [ hash ] = value ; } } class PersistentCache implements CacheManager { async get ( hash ) { return await getStorage ( ) . get ( hash ) ; } async set ( hash , value ) { getStorage ( ) . set ( hash , value ) ; } }