Остання активність 1 week ago

gistfile1.txt Неформатований
1import fs from "fs";
2import path from "path";
3import { TGResult, TGScore, Nation } from "../types";
4import { Nations } from "@systems/nations";
5import { Store } from "@systems/store";
6import { Paths } from "@helpers/paths";
7import { TGKey } from "@systems/tg-key";
8import { Logger } from "@systems/logger";
9const log = Logger.for("upsert-score");
10
11const HISTORY_DIR = path.join(__dirname, "../../data/tg-history");
12
13function historyPath(key: string): string {
14 return path.join(HISTORY_DIR, `${key}.json`);
15}
16
17export function loadResult(date: string, slot: number): TGResult | null {
18 const key = TGKey.from({ date, slot });
19 const p = historyPath(key);
20 log.debug(`loadResult: date=${date} slot=${slot} key=${key} path=${p}`);
21 return Store.read(p);
22}
23
24export function saveResult(result: TGResult): void {
25 if (!fs.existsSync(HISTORY_DIR)) fs.mkdirSync(HISTORY_DIR, { recursive: true });
26 const path = historyPath(TGKey.from({ date: result.date, slot: result.slot }));
27 Store.write(path, result);
28}
29
30export function upsertScore(score: TGScore): void {
31 const result = loadResult(score.date, score.slot) ?? {
32 slot: score.slot,
33 date: score.date,
34 confirmed: false,
35 nationKD: {
36 source: Nation.Procyon,
37 capella: { k: 0, d: 0 },
38 procyon: { k: 0, d: 0 },
39 },
40 scores: [],
41 };
42
43 // Overwrite existing score for this player+slot
44 result.scores = result.scores.filter(
45 (s) => !(s.userKey === score.userKey && s.characterName === score.characterName && s.slot === score.slot && s.date === score.date)
46 );
47 result.scores.push(score);
48 log.debug(`upsertScore: about to save — result.date=${result.date} result.slot=${result.slot}`);
49 saveResult(result);
50}