Create cache.ts

master
周炽键 3 years ago
commit eb781109e1

@ -0,0 +1,62 @@
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;
}
}
Loading…
Cancel
Save