enhance(frontend): improve some caches

This commit is contained in:
syuilo
2023-09-11 14:55:18 +09:00
parent cd6428715e
commit 25e030a707
8 changed files with 23 additions and 68 deletions

View File

@@ -9,9 +9,11 @@ export class Cache<T> {
private cachedAt: number | null = null;
public value = ref<T | undefined>();
private lifetime: number;
private fetcher: () => Promise<T>;
constructor(lifetime: Cache<never>['lifetime']) {
constructor(lifetime: Cache<never>['lifetime'], fetcher: () => Promise<T>) {
this.lifetime = lifetime;
this.fetcher = fetcher;
}
public set(value: T): void {
@@ -35,51 +37,17 @@ export class Cache<T> {
/**
* キャッシュがあればそれを返し、無ければfetcherを呼び出して結果をキャッシュ&返します
* optional: キャッシュが存在してもvalidatorでfalseを返すとキャッシュ無効扱いにします
*/
public async fetch(fetcher: () => Promise<T>, validator?: (cachedValue: T) => boolean): Promise<T> {
public async fetch(): Promise<T> {
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<T | undefined>, validator?: (cachedValue: T) => boolean): Promise<T | undefined> {
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;
}
}