You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.1 KiB
TypeScript

interface CacheDetail {
value: any;
expiresTimeStamp: number;
}
interface CacheMap {
[cacheKey: string]: CacheDetail;
}
/**
* 默认过期时间
*/
export const DEFAULT_EXPIRES = 5 * 60 * 1000;
let data: CacheMap = {};
export default class {
/**
* 插入指定名称数据
* @param {string} name
* @param {T} cache
* @param {number} expires 有效时间(毫秒时间戳)
*/
static set<T = any>(name: string, cache: T, expires: number = DEFAULT_EXPIRES) {
data[name] = {
value: cache,
expiresTimeStamp: Date.now() + expires,
};
return this;
}
static get<T = any>(name: string): T | null {
const detail = data[name];
if (!detail) return null;
try {
if (detail.expiresTimeStamp && detail.expiresTimeStamp > Date.now()) {
return detail.value || null;
}
} catch (err) {}
this.clear(name);
return null;
}
/**
* 获取指定名称数据
* @param {string} name
*/
static clear(name: string) {
delete data[name];
return this;
}
/**
* 清除所有数据
*/
static clearAll() {
data = {};
return this;
}
}