feat: some caching

This commit is contained in:
TrèsAbhi committed 2026-03-20 20:38:04 -05:00
1 parent c116b40dfc
commit e7337145d2
3 files changed
+37 -23

No files matched your search

+30 -19
View File
@@ -11,25 +11,8 @@ import type { TankList } from "../../protos/tank_list";
import type { Tanks } from "../../protos/tanks";
export abstract class AbstractAPI {
private _tankListCache: TankList | undefined;
protected abstract _tankList(): Promise<TankList>;
async tankList() {
if (this._tankListCache === undefined) {
this._tankListCache = await this._tankList();
}
return this._tankListCache;
}
private _tankCache: Record<string, Tank> = {};
protected abstract _tank(id: string): Promise<Tank>;
async tank(id: string) {
if (this._tankCache[id] === undefined) {
this._tankCache[id] = await this._tank(id);
}
return this._tankCache[id];
}
abstract tankList(): Promise<TankList>;
abstract tank(id: string): Promise<Tank>;
private _tanksCache: Tanks | undefined;
protected abstract _tanks(): Promise<Tanks>;
@@ -181,3 +164,31 @@ export abstract class AbstractAPI {
return this._popularTanksCache;
}
}
export function Cache(
discriminator: (...args: unknown[]) => string = () => "",
) {
const cache = new WeakMap<object, Map<string, unknown>>();
return function (
_target: unknown,
_propertyKey: string,
descriptor: PropertyDescriptor,
) {
const original = descriptor.value;
descriptor.value = async function (...args: unknown[]) {
const key = discriminator(...args);
const thisCache = cache.get(this) ?? new Map<string, unknown>();
if (!cache.has(this)) cache.set(this, thisCache);
if (thisCache.has(key)) return thisCache.get(key);
const result = await original.apply(this, args);
thisCache.set(key, result);
return result;
};
};
}
+5 -3
View File
@@ -15,7 +15,7 @@ import type { PopularTanks } from "../../protos/popular_tanks";
import type { Tank } from "../../protos/tank";
import type { TankListEntry } from "../../protos/tank_list";
import type { Tanks } from "../../protos/tanks";
import { AbstractAPI } from "./abstract";
import { AbstractAPI, Cache } from "./abstract";
if (typeof window !== "undefined") {
throw new Error("ServerAPI is being evaluated in the browser");
@@ -133,7 +133,8 @@ export class ServerAPI extends AbstractAPI {
return strings;
}
protected async _tankList() {
@Cache()
async tankList() {
const group = this.metadata.group("TankEntity");
const list: TankListEntry[] = [];
const strings = await this.groupedGameStrings("en", "TankEntity", true);
@@ -167,7 +168,8 @@ export class ServerAPI extends AbstractAPI {
return data;
}
protected async _tank(id: string) {
@Cache((id) => id)
async tank(id: string) {
const tankList = await this.tankList();
const tankListEntry = tankList.list.find((tank) => tank.id === id);
+2 -1
View File
@@ -17,7 +17,8 @@
"paths": {
"@protos/*": ["./packages/closed/protos/*"]
},
"strictNullChecks": true
"strictNullChecks": true,
"experimentalDecorators": true
},
"exclude": ["node_modules/**/*", "dist"]
}