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