import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { type Catalog, emptyCatalog } from "../domain/internship.js"; export interface Store { load(): Promise; save(value: T): Promise; } export type CatalogStore = Store; /** Объект в `/`; нет файла — пустое значение; запись атомарная (временный файл + rename). */ export class JsonFileStore implements Store { private readonly file: string; constructor( private readonly dir: string, file: string, private readonly empty: () => T, ) { this.file = path.join(dir, file); } async load(): Promise { try { const data = JSON.parse(await readFile(this.file, "utf8")) as Partial; return { ...this.empty(), ...data }; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return this.empty(); throw error; } } async save(value: T): Promise { await mkdir(this.dir, { recursive: true }); const tmp = `${this.file}.${process.pid}.tmp`; await writeFile(tmp, JSON.stringify(value, null, 2), "utf8"); await rename(tmp, this.file); } } /** Каталог стажировок в `/catalog.json`. */ export class JsonCatalogStore extends JsonFileStore { constructor(dir: string) { super(dir, "catalog.json", emptyCatalog); } }