summaryrefslogtreecommitdiff
path: root/src/misc/cache.ts
diff options
context:
space:
mode:
authorsyuilo <Syuilotan@yahoo.co.jp>2021-03-22 15:27:08 +0900
committersyuilo <Syuilotan@yahoo.co.jp>2021-03-22 15:27:08 +0900
commit52d577c7dd7bf87b3fae34f539bb6e656c7c0ed2 (patch)
tree9805c625a7fba9d8631db8a92772b2772d8632ec /src/misc/cache.ts
parentMerge branch 'develop' (diff)
parent12.75.0 (diff)
downloadmisskey-52d577c7dd7bf87b3fae34f539bb6e656c7c0ed2.tar.gz
misskey-52d577c7dd7bf87b3fae34f539bb6e656c7c0ed2.tar.bz2
misskey-52d577c7dd7bf87b3fae34f539bb6e656c7c0ed2.zip
Merge branch 'develop'
Diffstat (limited to 'src/misc/cache.ts')
-rw-r--r--src/misc/cache.ts43
1 files changed, 43 insertions, 0 deletions
diff --git a/src/misc/cache.ts b/src/misc/cache.ts
new file mode 100644
index 0000000000..71fbbd8a4c
--- /dev/null
+++ b/src/misc/cache.ts
@@ -0,0 +1,43 @@
+export class Cache<T> {
+ private cache: Map<string | null, { date: number; value: T; }>;
+ private lifetime: number;
+
+ constructor(lifetime: Cache<never>['lifetime']) {
+ this.cache = new Map();
+ this.lifetime = lifetime;
+ }
+
+ public set(key: string | null, value: T): void {
+ this.cache.set(key, {
+ date: Date.now(),
+ value
+ });
+ }
+
+ public get(key: string | null): T | undefined {
+ const cached = this.cache.get(key);
+ if (cached == null) return undefined;
+ if ((Date.now() - cached.date) > this.lifetime) {
+ this.cache.delete(key);
+ return undefined;
+ }
+ return cached.value;
+ }
+
+ public delete(key: string | null) {
+ this.cache.delete(key);
+ }
+
+ public async fetch(key: string | null, fetcher: () => Promise<T>): Promise<T> {
+ const cachedValue = this.get(key);
+ if (cachedValue !== undefined) {
+ // Cache HIT
+ return cachedValue;
+ }
+
+ // Cache MISS
+ const value = await fetcher();
+ this.set(key, value);
+ return value;
+ }
+}