peppa/bench/base/product/lib/store.mjs
2026-11-17 02:09:17 +05:00

43 lines
1.3 KiB
JavaScript

// Хранилище: коллекции записей в JSON-файлах каталога $DATA_DIR (по умолчанию product/data).
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { join } from "node:path";
function dataDir() {
return process.env.DATA_DIR || new URL("../data/", import.meta.url).pathname;
}
export function collection(name) {
const file = () => join(dataDir(), `${name}.json`);
const load = () => {
try {
return JSON.parse(readFileSync(file(), "utf8"));
} catch {
return [];
}
};
const save = (rows) => {
mkdirSync(dataDir(), { recursive: true });
writeFileSync(`${file()}.tmp`, JSON.stringify(rows, null, 2));
renameSync(`${file()}.tmp`, file());
};
return {
all: () => load(),
get: (id) => load().find((r) => String(r.id) === String(id)) ?? null,
add(fields) {
const rows = load();
const row = { id: rows.reduce((m, r) => Math.max(m, Number(r.id) || 0), 0) + 1, ...fields };
rows.push(row);
save(rows);
return row;
},
update(id, patch) {
const rows = load();
const i = rows.findIndex((r) => String(r.id) === String(id));
if (i < 0) return null;
rows[i] = { ...rows[i], ...patch, id: rows[i].id };
save(rows);
return rows[i];
},
};
}