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