2023-07-27 14:31:52 +09:00
|
|
|
/*
|
|
|
|
* SPDX-FileCopyrightText: syuilo and other misskey contributors
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
|
|
|
import { ref } from 'vue';
|
2023-03-24 16:54:37 +09:00
|
|
|
|
|
|
|
export class Cache<T> {
|
|
|
|
private cachedAt: number | null = null;
|
2023-07-10 15:55:10 +09:00
|
|
|
public value = ref<T | undefined>();
|
2023-03-24 16:54:37 +09:00
|
|
|
private lifetime: number;
|
2023-09-11 14:55:18 +09:00
|
|
|
private fetcher: () => Promise<T>;
|
2023-03-24 16:54:37 +09:00
|
|
|
|
2023-09-11 14:55:18 +09:00
|
|
|
constructor(lifetime: Cache<never>['lifetime'], fetcher: () => Promise<T>) {
|
2023-03-24 16:54:37 +09:00
|
|
|
this.lifetime = lifetime;
|
2023-09-11 14:55:18 +09:00
|
|
|
this.fetcher = fetcher;
|
2023-03-24 16:54:37 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
public set(value: T): void {
|
|
|
|
this.cachedAt = Date.now();
|
2023-07-10 15:55:10 +09:00
|
|
|
this.value.value = value;
|
2023-03-24 16:54:37 +09:00
|
|
|
}
|
|
|
|
|
2023-07-10 15:55:10 +09:00
|
|
|
private get(): T | undefined {
|
2023-03-24 16:54:37 +09:00
|
|
|
if (this.cachedAt == null) return undefined;
|
|
|
|
if ((Date.now() - this.cachedAt) > this.lifetime) {
|
2023-07-10 15:55:10 +09:00
|
|
|
this.value.value = undefined;
|
2023-03-24 16:54:37 +09:00
|
|
|
this.cachedAt = null;
|
|
|
|
return undefined;
|
|
|
|
}
|
2023-07-10 15:55:10 +09:00
|
|
|
return this.value.value;
|
2023-03-24 16:54:37 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
public delete() {
|
|
|
|
this.cachedAt = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* キャッシュがあればそれを返し、無ければfetcherを呼び出して結果をキャッシュ&返します
|
|
|
|
*/
|
2023-09-11 14:55:18 +09:00
|
|
|
public async fetch(): Promise<T> {
|
2023-03-24 16:54:37 +09:00
|
|
|
const cachedValue = this.get();
|
|
|
|
if (cachedValue !== undefined) {
|
2023-09-11 14:55:18 +09:00
|
|
|
// Cache HIT
|
|
|
|
return cachedValue;
|
2023-03-24 16:54:37 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
// Cache MISS
|
2023-09-11 14:55:18 +09:00
|
|
|
const value = await this.fetcher();
|
2023-03-24 16:54:37 +09:00
|
|
|
this.set(value);
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
}
|