shablony-prodavanam/src/store.js
Peppa 27a8c00cf5
Some checks failed
peppa/install install: failure за 0с
ci / checks (pull_request) Failing after 4s
deploy / deploy (pull_request) Successful in 18s
SP-1: лендинг, бот с ручным подтверждением Kaspi, генератор финмодели
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 16:16:49 +05:00

54 lines
1.6 KiB
JavaScript

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();
}
}