techtools

http.ts

TypeScript · 107 рядків

1// Операція = контракт + функція. HTTP, транзакція, трасування й помилки — тут, один раз для всіх операцій.
2//
3//   export default feature({ name, method, path, summary, input: z.object(...), tx: 'write', run: (sql, input) => ... })
4//
5// Запит:   GET — вхід із query + path; POST/DELETE — з body + path. Вхід перевіряє zod-схема операції.
6// Прапорці (лише для сторінки):
7//   ?trace=1  — { result, trace: { ms, dbMs, statements[], before, after } }: SQL операції з часом і стан товару до/після;
8//   ?dryRun=1 — виконати в транзакції й відкотити (попередній перегляд змін).
9// Без прапорців відповідь — сам результат, без жодних додаткових запитів.
10import type { Request, Response, Router } from 'express';
11import { z } from 'zod';
12import type { Database, Sql, Statement } from './db.ts';
13import { AppError, toErrorResponse } from './errors.ts';
14
15export type TxMode = 'none' | 'write';
16
17export interface Feature<I = any, O = any> {
18  name: string;
19  method: 'GET' | 'POST' | 'DELETE';
20  path: string;
21  summary: string;
22  input: z.ZodType<I>;
23  /** write — уся операція в одній транзакції; none — запити окремо (читання, обслуговування з власними транзакціями). */
24  tx: TxMode;
25  /** Лише для демо-сервера (скидання даних). */
26  demoOnly?: boolean;
27  /** Товари, стан яких показати до/після при ?trace=1. */
28  affects?: (input: I) => number[];
29  run: (sql: Sql, input: I) => Promise<O>;
30}
31
32export function feature<I, O>(f: Feature<I, O>): Feature<I, O> {
33  return f;
34}
35
36export type Snapshot = (sql: Sql, productId: number) => Promise<unknown>;
37
38export interface MountOptions { db: Database; snapshot: Snapshot; demo: boolean }
39
40export function mount(router: Router, features: Feature[], o: MountOptions): void {
41  for (const f of features) {
42    if (f.demoOnly && !o.demo) continue;
43    const handler = (req: Request, res: Response) => handle(f, req, res, o);
44    if (f.method === 'GET') router.get(f.path, handler);
45    else if (f.method === 'POST') router.post(f.path, handler);
46    else router.delete(f.path, handler);
47  }
48}
49
50async function handle(f: Feature, req: Request, res: Response, o: MountOptions): Promise<void> {
51  const trace = req.query.trace === '1';
52  const dryRun = req.query.dryRun === '1';
53  const statements: Statement[] = [];
54  try {
55    const raw = { ...(f.method === 'GET' ? req.query : req.body), ...req.params };
56    delete raw.trace;
57    delete raw.dryRun;
58    const input = f.input.parse(raw);
59    if (dryRun && f.tx !== 'write') throw new AppError(400, 'DRY_RUN_UNSUPPORTED', `Операція ${f.name} не транзакційна — попередній перегляд неможливий`);
60
61    if (!trace && !dryRun) {
62      res.json(f.tx === 'write' ? await o.db.transaction((sql) => f.run(sql, input)) : await f.run(o.db.sql(), input));
63      return;
64    }
65
66    const started = performance.now();
67    if (f.tx === 'none') {
68      const t = performance.now();
69      const result = await f.run(o.db.sql(statements), input);
70      res.json({ result, trace: summary(statements, performance.now() - t, performance.now() - started, false) });
71      return;
72    }
73    const ids = trace && f.affects ? [...new Set(f.affects(input))] : [];
74    const out = await o.db.transaction(async (sql, plain) => {
75      const before = await snapshots(plain, ids, o.snapshot);
76      const t = performance.now();
77      const result = await f.run(sql, input);
78      const ms = performance.now() - t;
79      const after = await snapshots(plain, ids, o.snapshot);
80      return { result, ms, before, after };
81    }, { dryRun }, statements);
82    res.json({ result: out.result, trace: { ...summary(statements, out.ms, performance.now() - started, dryRun), before: out.before, after: out.after } });
83  } catch (e) {
84    const { status, body } = toErrorResponse(e);
85    if (status >= 500) console.error(JSON.stringify({ feature: f.name, code: body.code, message: body.message, stack: (e as Error)?.stack }));
86    res.status(status).json({ error: trace ? { ...body, statements } : body });
87  }
88}
89
90async function snapshots(sql: Sql, ids: number[], snapshot: Snapshot): Promise<Record<number, unknown>> {
91  const out: Record<number, unknown> = {};
92  for (const id of ids) out[id] = await snapshot(sql, id);
93  return out;
94}
95
96function summary(statements: Statement[], ms: number, totalMs: number, dryRun: boolean) {
97  return { ms, totalMs, dbMs: statements.reduce((s, x) => s + x.ms, 0), dryRun, statements };
98}
99
100/** Опис усіх операцій для людей і агентів: GET /api/contract. */
101export function contract(features: Feature[], demo: boolean) {
102  return features.filter((f) => demo || !f.demoOnly).map((f) => ({
103    name: f.name, method: f.method, path: f.path, summary: f.summary, tx: f.tx, demoOnly: !!f.demoOnly,
104    input: z.toJSONSchema(f.input, { unrepresentable: 'any', io: 'input' }),
105  }));
106}
107