Files
OpenFrontIO/src/core/game/FetchGameMapLoader.ts
T
Scott Anderson 7e25f6b910 Enable @total-typescript/ts-reset (#1761)
## Description:

Enable `@total-typescript/ts-reset`

Fixes #1760

## Please complete the following:

- [x] I have added screenshots for all UI updates
- [x] I process any text displayed to the user through translateText()
and I've added it to the en.json file
- [x] I have added relevant tests to the test directory
- [x] I confirm I have thoroughly tested these changes and take full
responsibility for any bugs introduced
- [ ] I have read and accepted the CLA agreement (only required once).
2025-08-09 02:13:56 -04:00

73 lines
1.9 KiB
TypeScript

import { GameMapType } from "./Game";
import { GameMapLoader, MapData } from "./GameMapLoader";
import { MapManifestSchema } from "./TerrainMapLoader";
export class FetchGameMapLoader implements GameMapLoader {
private maps: Map<GameMapType, MapData>;
public constructor(
private readonly prefix: string,
private readonly cacheBuster?: string,
) {
this.maps = new Map<GameMapType, MapData>();
}
public getMapData(map: GameMapType): MapData {
const cachedMap = this.maps.get(map);
if (cachedMap) {
return cachedMap;
}
const key = Object.keys(GameMapType).find(
(k) => GameMapType[k as keyof typeof GameMapType] === map,
);
const fileName = key?.toLowerCase();
if (!fileName) {
throw new Error(`Unknown map: ${map}`);
}
const mapData = {
manifest: () => this.loadJsonFromUrl(this.url(fileName, "manifest.json")),
mapBin: () => this.loadBinaryFromUrl(this.url(fileName, "map.bin")),
miniMapBin: () =>
this.loadBinaryFromUrl(this.url(fileName, "mini_map.bin")),
webpPath: async () => this.url(fileName, "thumbnail.webp"),
} satisfies MapData;
this.maps.set(map, mapData);
return mapData;
}
private url(map: string, path: string) {
let url = `${this.prefix}/${map}/${path}`;
if (this.cacheBuster) {
url += `${url.includes("?") ? "&" : "?"}v=${this.cacheBuster}`;
}
return url;
}
private async loadBinaryFromUrl(url: string) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to load ${url}: ${response.statusText}`);
}
const data = await response.arrayBuffer();
return new Uint8Array(data);
}
private async loadJsonFromUrl(url: string) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to load ${url}: ${response.statusText}`);
}
return response.json().then(MapManifestSchema.parse);
}
}