techtools

client.ts

TypeScript · 66 рядків

1// HTTP-клієнт API для скриптів і тестів: node:http з keep-alive (fetch на Windows додає ~15 мс на запит — R-02 §4.1).
2// Шляхи пишуться рядком як у features/*.ts — grep '/api/receipts' знаходить і операцію, і всіх її викликачів.
3import http from 'node:http';
4
5export class ApiError extends Error {
6  readonly status: number;
7  readonly code: string;
8  readonly body: unknown;
9
10  constructor(status: number, body: any) {
11    super(`${status} ${body?.error?.code ?? ''}: ${body?.error?.message ?? JSON.stringify(body)}`);
12    this.status = status;
13    this.code = body?.error?.code ?? 'HTTP';
14    this.body = body;
15  }
16}
17
18export class Api {
19  readonly base: URL;
20  private readonly agent: http.Agent;
21
22  constructor(url: string, maxSockets = 64) {
23    this.base = new URL(url);
24    this.agent = new http.Agent({ keepAlive: true, maxSockets });
25  }
26
27  get<T = any>(path: string, query: Record<string, unknown> = {}): Promise<T> {
28    const q = Object.entries(query).filter(([, v]) => v !== undefined && v !== null).map(([k, v]) => `${k}=${encodeURIComponent(String(v))}`).join('&');
29    return this.request<T>('GET', q ? `${path}?${q}` : path);
30  }
31
32  post<T = any>(path: string, body: unknown = {}): Promise<T> {
33    return this.request<T>('POST', path, body);
34  }
35
36  delete<T = any>(path: string): Promise<T> {
37    return this.request<T>('DELETE', path);
38  }
39
40  request<T>(method: string, path: string, body?: unknown): Promise<T> {
41    const data = body === undefined ? undefined : Buffer.from(JSON.stringify(body));
42    return new Promise<T>((resolve, reject) => {
43      const req = http.request({
44        host: this.base.hostname, port: this.base.port, path, method, agent: this.agent,
45        headers: data ? { 'content-type': 'application/json', 'content-length': data.length } : {},
46      }, (res) => {
47        const chunks: Buffer[] = [];
48        res.on('data', (c) => chunks.push(c));
49        res.on('end', () => {
50          const text = Buffer.concat(chunks).toString('utf8');
51          const json = text ? JSON.parse(text) : null;
52          if ((res.statusCode ?? 500) >= 400) reject(new ApiError(res.statusCode ?? 500, json));
53          else resolve(json as T);
54        });
55      });
56      req.on('error', reject);
57      if (data) req.write(data);
58      req.end();
59    });
60  }
61
62  close(): void {
63    this.agent.destroy();
64  }
65}
66