Create cache.ts

This commit is contained in:
周炽键 2021-02-18 14:48:18 +08:00
commit eb781109e1
1 changed files with 62 additions and 0 deletions

62
cache.ts Normal file
View File

@ -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;
}
}