techtools

client.ts

TypeScript · 28 рядків

1import { Agent, request, type IncomingHttpHeaders } from 'node:http';
2
3// HTTP-клієнт на node:http з keep-alive. Вбудований fetch на Windows додає ~15 мс на запит (крок таймера ОС),
4// що спотворює заміри; node:http на тому ж запиті — ~0.2 мс.
5export interface Resp { status: number; headers: IncomingHttpHeaders; body: any }
6
7export function httpClient(base: string): { call: (method: string, path: string, body?: unknown) => Promise<Resp>; close: () => void } {
8  const u = new URL(base);
9  const agent = new Agent({ keepAlive: true, maxSockets: 1 });
10  const call = (method: string, path: string, body?: unknown) => new Promise<Resp>((resolve, reject) => {
11    const payload = body === undefined ? undefined : JSON.stringify(body);
12    const rq = request({ host: u.hostname, port: u.port, method, path, agent, headers: payload ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) } : {} }, (res) => {
13      const chunks: Buffer[] = [];
14      res.on('data', (c: Buffer) => chunks.push(c));
15      res.on('end', () => {
16        try {
17          resolve({ status: res.statusCode ?? 0, headers: res.headers, body: JSON.parse(Buffer.concat(chunks).toString('utf8')) });
18        } catch (e) {
19          reject(e);
20        }
21      });
22    });
23    rq.on('error', reject);
24    rq.end(payload);
25  });
26  return { call, close: () => agent.destroy() };
27}
28