Skip to content

Commit

Permalink
feat(Cache.ts): 新增deleteByTag通过tag删除缓存的功能
Browse files Browse the repository at this point in the history
  • Loading branch information
mengxinssfd committed Aug 15, 2022
1 parent 087230f commit fcea8fc
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions src/Cache.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import type { Tag } from './types';

/**
* @public
*/
export class Cache<V> {
constructor(protected readonly cache = new Map<any, { value: V; expires: number }>()) {}
constructor(
protected readonly cache = new Map<any, { value: V; tag?: Tag; expires: number }>(),
protected readonly tagMap = new Map<Tag, Set<string>>(),
) {}

clearDeadCache() {
const now = Date.now();
for (const [k, v] of this.cache.entries()) {
if (v.expires > now) continue;
this.cache.delete(k);
this.delete(k);
}
}

Expand All @@ -17,19 +22,35 @@ export class Cache<V> {
if (!v) return null;
const now = Date.now();
if (now > v.expires) {
this.cache.delete(key);
this.delete(key);
return null;
}
return v.value;
}

set(key: any, value: V, { timeout = 5 * 1000 }: { timeout?: number } = {}) {
this.cache.set(key, { value, expires: timeout + Date.now() });
set(key: any, value: V, { timeout = 5 * 1000, tag }: { timeout?: number; tag?: Tag } = {}) {
if (tag) {
if (!this.tagMap.has(tag)) this.tagMap.set(tag, new Set());
(this.tagMap.get(tag) as Set<string>).add(key);
}
this.cache.set(key, { value, tag, expires: timeout + Date.now() });
this.clearDeadCache();
}

delete(key: any) {
const value = this.cache.get(key);
this.cache.delete(key);
if (value?.tag) {
this.tagMap.get(value.tag)?.delete(key);
}
}

deleteByTag(tag: Tag) {
const keys = this.tagMap.get(tag);
keys?.forEach((key) => {
this.cache.delete(key);
});
this.tagMap.delete(tag);
}

has(key: any): boolean {
Expand Down

0 comments on commit fcea8fc

Please sign in to comment.