techtools

api.ts

TypeScript · 78 рядків

1import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2import { openDb } from './db.ts';
3import { ApiError, Inventory, type InventoryOptions } from './inventory.ts';
4
5// Мікро-API над SQLite. Пакетні ендпоінти приймають масиви, кожен рядок — окрема транзакція БД.
6export function createApi(dbFile: string, sync: 'OFF' | 'NORMAL' | 'FULL' = 'OFF', opts: InventoryOptions = {}): { server: Server; inv: Inventory } {
7  const inv = new Inventory(openDb(dbFile, sync), opts);
8
9  const routes: Record<string, (body: any, url: URL) => unknown> = {
10    'POST /products': (b) => inv.addProducts(b),
11    'POST /receipts': (b) => (b as any[]).map((r) => inv.receive(r)),
12    // orderTx: усе замовлення — одна транзакція БД (один fsync), інакше — транзакція на рядок.
13    'POST /issues': (b) => inv.opts.orderTx
14      ? inv.tx(() => (b.lines as any[]).map((l) => safe(() => inv.issue(l, b.day, true))))
15      : (b.lines as any[]).map((l) => safe(() => inv.issue(l, b.day))),
16    'POST /returns': (b) => (b.lines as any[]).map((l) => safe(() => inv.returnItem(l, b.day))),
17    'POST /adjustments': (b) => (b.lines as any[]).map((l) => safe(() => inv.adjust(l.item_id, l.delta, b.day, l.reason, l.serials))),
18    'POST /labels': (b) => (b.lines as any[]).map((l) => safe(() => inv.label(l.item_id, l.label ?? null, b.day))),
19    'POST /maintenance/expire': (b) => inv.expire(b.day),
20    'POST /maintenance/write-off-expired': (b) => inv.writeOffExpired(b.day, b.doc),
21    'POST /maintenance/repack': (b) => inv.repack(b.day, b.min_packs),
22    'GET /stock': (_b, u) => {
23      const id = u.searchParams.get('product_id');
24      const brand = u.searchParams.get('brand');
25      if (id || brand) return inv.stock({ product_id: id ? Number(id) : undefined, brand: brand ?? undefined, sku: u.searchParams.get('sku') ?? undefined });
26      return inv.stockSummary();
27    },
28    'GET /items': (_b, u) => inv.items(Number(u.searchParams.get('product_id'))),
29    'GET /genealogy': (_b, u) => inv.genealogy(Number(u.searchParams.get('id'))),
30    'GET /reconcile': () => inv.reconcile(),
31    'GET /stats': () => inv.stats(),
32    'GET /expiry-report': (_b, u) => inv.expiryReport(Number(u.searchParams.get('day'))),
33    'GET /profile': () => ({ sql: inv.profileReport(), recordsPerProduct: inv.recordsPerProduct() }),
34  };
35
36  const server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
37    const url = new URL(req.url ?? '/', 'http://local');
38    const handler = routes[`${req.method} ${url.pathname}`];
39    try {
40      if (!handler) throw new ApiError(404, `немає маршруту ${req.method} ${url.pathname}`);
41      const body = req.method === 'POST' ? JSON.parse(await readBody(req) || 'null') : null;
42      // Заміри: час обробника (без мережі й парсингу) і кількість SQL-операторів — у заголовках відповіді.
43      const ops0 = inv.ops;
44      const t0 = performance.now();
45      const data = handler(body, url);
46      send(res, 200, data, { 'x-handler-ms': (performance.now() - t0).toFixed(3), 'x-db-ops': String(inv.ops - ops0) });
47    } catch (e) {
48      const status = e instanceof ApiError ? e.status : 500;
49      send(res, status, { error: (e as Error).message });
50    }
51  });
52  return { server, inv };
53}
54
55function safe<T>(fn: () => T): T | { error: string; status: number } {
56  try {
57    return fn();
58  } catch (e) {
59    if (e instanceof ApiError) return { error: e.message, status: e.status };
60    throw e;
61  }
62}
63
64function readBody(req: IncomingMessage): Promise<string> {
65  return new Promise((resolve, reject) => {
66    const chunks: Buffer[] = [];
67    req.on('data', (c: Buffer) => chunks.push(c));
68    req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
69    req.on('error', reject);
70  });
71}
72
73function send(res: ServerResponse, status: number, data: unknown, headers: Record<string, string> = {}): void {
74  const json = JSON.stringify(data);
75  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', ...headers });
76  res.end(json);
77}
78