28 lines
1.3 KiB
TypeScript
28 lines
1.3 KiB
TypeScript
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
import { dirname } from "node:path";
|
|
import type { EventRecord } from "./types.js";
|
|
|
|
interface PersistedEvents { version: 1; events: Record<string, number>; }
|
|
const MAX_EVENTS = 2000;
|
|
|
|
export class EventStore {
|
|
constructor(private readonly filePath: string) {}
|
|
private read(): PersistedEvents {
|
|
if (!existsSync(this.filePath)) return { version: 1, events: {} };
|
|
try {
|
|
const parsed = JSON.parse(readFileSync(this.filePath, "utf8")) as Partial<PersistedEvents>;
|
|
return { version: 1, events: parsed.events && typeof parsed.events === "object" ? parsed.events : {} };
|
|
} catch { return { version: 1, events: {} }; }
|
|
}
|
|
has(id: string): boolean { return Object.prototype.hasOwnProperty.call(this.read().events, id); }
|
|
commit(records: EventRecord[]): void {
|
|
if (!records.length) return;
|
|
const data = this.read();
|
|
const merged = { ...data.events };
|
|
for (const record of records) merged[record.id] = record.observedAt;
|
|
const entries = Object.entries(merged).sort((a, b) => a[1] - b[1]).slice(-MAX_EVENTS);
|
|
mkdirSync(dirname(this.filePath), { recursive: true, mode: 0o700 });
|
|
writeFileSync(this.filePath, `${JSON.stringify({ version: 1, events: Object.fromEntries(entries) }, null, 2)}\n`, { mode: 0o600 });
|
|
}
|
|
}
|