import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { join } from "node:path"; // Заказы в JSON-файле. Заказов единицы, поэтому БД не нужна; запись атомарная (tmp + rename). export class Store { constructor(dir) { this.file = join(dir, "orders.json"); this.dir = dir; this.state = { nextId: 1, orders: [], offset: 0 }; this.queue = Promise.resolve(); } async load() { try { this.state = JSON.parse(await readFile(this.file, "utf8")); } catch (e) { if (e.code !== "ENOENT") throw e; } return this; } save() { this.queue = this.queue.then(async () => { await mkdir(this.dir, { recursive: true }); const tmp = `${this.file}.tmp`; await writeFile(tmp, JSON.stringify(this.state, null, 2)); await rename(tmp, this.file); }); return this.queue; } async createOrder(data) { const order = { id: this.state.nextId++, status: "pending", createdAt: new Date().toISOString(), ...data }; this.state.orders.push(order); await this.save(); return order; } get(id) { return this.state.orders.find((o) => o.id === Number(id)); } lastByBuyer(buyerId) { return [...this.state.orders].reverse().find((o) => String(o.buyerId) === String(buyerId)); } async update(id, patch) { Object.assign(this.get(id), patch); await this.save(); return this.get(id); } get offset() { return this.state.offset; } async setOffset(n) { this.state.offset = n; await this.save(); } }