From eb781109e1fefabb453f6ea2ee5aa71cc9e5546e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=91=A8=E7=82=BD=E9=94=AE?= <397201698@qq.com> Date: Thu, 18 Feb 2021 14:48:18 +0800 Subject: [PATCH] Create cache.ts --- cache.ts | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 cache.ts diff --git a/cache.ts b/cache.ts new file mode 100644 index 0000000..1791f48 --- /dev/null +++ b/cache.ts @@ -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(name: string, cache: T, expires: number = DEFAULT_EXPIRES) { + data[name] = { + value: cache, + expiresTimeStamp: Date.now() + expires, + }; + return this; + } + + static get(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; + } +}