From 25e030a7074f8e00cfbdaf85e491b9b22886991d Mon Sep 17 00:00:00 2001 From: syuilo Date: Mon, 11 Sep 2023 14:55:18 +0900 Subject: enhance(frontend): improve some caches --- packages/frontend/src/scripts/cache.ts | 46 ++++++---------------------------- 1 file changed, 7 insertions(+), 39 deletions(-) (limited to 'packages/frontend/src/scripts/cache.ts') diff --git a/packages/frontend/src/scripts/cache.ts b/packages/frontend/src/scripts/cache.ts index 0dda203ef0..12347cf4b1 100644 --- a/packages/frontend/src/scripts/cache.ts +++ b/packages/frontend/src/scripts/cache.ts @@ -9,9 +9,11 @@ export class Cache { private cachedAt: number | null = null; public value = ref(); private lifetime: number; + private fetcher: () => Promise; - constructor(lifetime: Cache['lifetime']) { + constructor(lifetime: Cache['lifetime'], fetcher: () => Promise) { this.lifetime = lifetime; + this.fetcher = fetcher; } public set(value: T): void { @@ -35,51 +37,17 @@ export class Cache { /** * キャッシュがあればそれを返し、無ければfetcherを呼び出して結果をキャッシュ&返します - * optional: キャッシュが存在してもvalidatorでfalseを返すとキャッシュ無効扱いにします */ - public async fetch(fetcher: () => Promise, validator?: (cachedValue: T) => boolean): Promise { + public async fetch(): Promise { const cachedValue = this.get(); if (cachedValue !== undefined) { - if (validator) { - if (validator(cachedValue)) { - // Cache HIT - return cachedValue; - } - } else { - // Cache HIT - return cachedValue; - } + // Cache HIT + return cachedValue; } // Cache MISS - const value = await fetcher(); + const value = await this.fetcher(); this.set(value); return value; } - - /** - * キャッシュがあればそれを返し、無ければfetcherを呼び出して結果をキャッシュ&返します - * optional: キャッシュが存在してもvalidatorでfalseを返すとキャッシュ無効扱いにします - */ - public async fetchMaybe(fetcher: () => Promise, validator?: (cachedValue: T) => boolean): Promise { - const cachedValue = this.get(); - if (cachedValue !== undefined) { - if (validator) { - if (validator(cachedValue)) { - // Cache HIT - return cachedValue; - } - } else { - // Cache HIT - return cachedValue; - } - } - - // Cache MISS - const value = await fetcher(); - if (value !== undefined) { - this.set(value); - } - return value; - } } -- cgit v1.2.3-freya