mirror of
				https://github.com/soybeanjs/soybean-admin.git
				synced 2025-11-04 15:53:43 +08:00 
			
		
		
		
	feat(storage): local存储增加有效期
This commit is contained in:
		@@ -1,12 +1,21 @@
 | 
			
		||||
export function setLocal(key: string, value: unknown) {
 | 
			
		||||
  const json = JSON.stringify(value);
 | 
			
		||||
/** 默认缓存期限为7天 */
 | 
			
		||||
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;
 | 
			
		||||
 | 
			
		||||
export function setLocal(key: string, value: unknown, expire: number | null = DEFAULT_CACHE_TIME) {
 | 
			
		||||
  const json = JSON.stringify({ value, expire: expire !== null ? new Date().getTime() + expire * 1000 : null });
 | 
			
		||||
  window.localStorage.setItem(key, json);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export function getLocal<T>(key: string) {
 | 
			
		||||
  const json = window.localStorage.getItem(key);
 | 
			
		||||
  if (json) {
 | 
			
		||||
    return JSON.parse(json) as T;
 | 
			
		||||
    const data = JSON.parse(json);
 | 
			
		||||
    const { value, expire } = data;
 | 
			
		||||
    /** 在有效期内直接返回 */
 | 
			
		||||
    if (expire === null || expire >= Date.now()) {
 | 
			
		||||
      return value as T;
 | 
			
		||||
    }
 | 
			
		||||
    removeLocal(key);
 | 
			
		||||
  }
 | 
			
		||||
  return null;
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user