ez-store 以简单,统一的方式使用localStorage
、sessionStorage
、内存对象。
import EzStore from '@easyevery/ez-store';
export const activeCache = EzStore.createLocal<boolean>('active-a', {
prefix: '平台A',
});
// 使用同步缓存项
activeCache.set(true);
activeCache.get();
import EzStore from '@easyevery/ez-store';
export const asyncCache = EzStore.createSession('test', {
getter: async () => {
return Promise.resolve({ id: 1 });
},
expire: EzStore.TimeSpan.day * 2, // 2天后过期
});
// 使用异步缓存项
await asyncCache.get();
await asyncCache.set({ id: 2 });
注意:
getter: 异步缓存项优先从 cache 中取值,若没有则调用 getter 方法。
setter: 异步缓存项优使用 setter 的返回值来设置缓存的值
export const requestCache = EzStore.createLocal<boolean>('request', {
prefix: '平台A',
expire: dayjs().add('day', 1).valueOf(), // 1天后过期
});
type Cache = Readonly<{
name: string;
get: () => T | null;
set: (value: T) => boolean;
remove: () => boolean;
}>;
type IStoreOptions = { prefix?: string; version?: number; expire?: number };
function CreateCacheImp<T = any>(
key: string,
options?: IStoreOptions & {
getter?: ((params: any) => Promise<T>) | (() => null);
setter?: ((value: T) => Promise<T>) | ((val: T) => T);
},
): Cache;
enum TimeSpan {
second = 1000,
minute = 60 * 1000,
hour = 3600 * 1000,
day = 24 * 3600 * 1000,
week = 7 * 24 * 3600 * 1000,
month = 30 * 24 * 3600 * 1000,
year = 365 * 24 * 3600 * 1000,
}
方法 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
createLocal | 基于localStorate的同步缓存 | CreateCacheImp | - | - |
createSession | 基于sessionStorate的同步缓存 | CreateCacheImp | - | - |
createMemory | 基于内存的的同步缓存 | CreateCacheImp | - | - |
createAsyncLocal | 基于localStorate的异步缓存 | CreateCacheImp | - | - |
createAsyncSession | 基于sessionStorate的异步缓存 | CreateCacheImp | - | - |
createAsyncMemory | 基于内存的的异步缓存 | CreateCacheImp | - | - |
参数 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
key | 缓存的key | string |
- | - |
options | 缓存的options | IStoreOptions | - | - |
type StoreType = 'localStorage' | 'sessionStorage' | 'memory';
function SyncCacheImp<T = any>(
type: StoreType,
key: string,
options?: IStoreOptions & {
getter?: ((params: any) => Promise<T>) | (() => null);
setter?: ((value: T) => Promise<T>) | ((val: T) => T);
},
): Cache;
方法 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
createSyncCache | 根据type创建同步的缓存 | SyncCacheImp | - | - |
createAsyncCache | 根据type创建异步的缓存 | SyncCacheImp | - | - |
相比 createLocal、createAsyncLocal 等方法,只是多了第一个参数 type
,但返回值都是缓存项Cache
。
参数 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
type | 缓存的类型 | StoreType | - | - |
key | 缓存的key | string | - | - |
options | 缓存的options | IStoreOptions | - | - |
参数 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
options | options | {prefix:string} | - | - |
参数 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
name | 获取缓存的key | string | - | - |
get | 获取缓存的值 | () => T | null; | - |
set | 设置缓存的值 | (value: T) => boolean; | - | - |
remove | 移除缓存的值 | () => boolean; | - | - |
npm i @easyevery/ez-store
yarn add @easyevery/ez-store
MIT