freetravel/src/store/catalogStore.ts

48 lines
1.4 KiB
TypeScript

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<T> {
load(): Promise<T>;
save(value: T): Promise<void>;
}
export type CatalogStore = Store<Catalog>;
/** Объект в `<dir>/<file>`; нет файла — пустое значение; запись атомарная (временный файл + rename). */
export class JsonFileStore<T extends object> implements Store<T> {
private readonly file: string;
constructor(
private readonly dir: string,
file: string,
private readonly empty: () => T,
) {
this.file = path.join(dir, file);
}
async load(): Promise<T> {
try {
const data = JSON.parse(await readFile(this.file, "utf8")) as Partial<T>;
return { ...this.empty(), ...data };
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return this.empty();
throw error;
}
}
async save(value: T): Promise<void> {
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);
}
}
/** Каталог стажировок в `<dir>/catalog.json`. */
export class JsonCatalogStore extends JsonFileStore<Catalog> {
constructor(dir: string) {
super(dir, "catalog.json", emptyCatalog);
}
}