@tcds-io/http-client 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -2
- package/dist/index.d.ts +6 -0
- package/dist/index.js +3 -0
- package/dist/json-http-client.d.ts +58 -0
- package/dist/json-http-client.js +132 -0
- package/dist/multipart.d.ts +16 -0
- package/dist/multipart.js +21 -0
- package/dist/reveal.d.ts +2 -0
- package/dist/reveal.js +14 -0
- package/dist/testing.d.ts +41 -0
- package/dist/testing.js +84 -0
- package/dist/types.d.ts +25 -0
- package/dist/types.js +1 -0
- package/package.json +46 -3
package/README.md
CHANGED
|
@@ -1,3 +1,42 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tcds-io/http-client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A JSON `fetch` client for partner APIs, with a test double. It throws [`@tcds-io/domain`](../domain) errors that carry the partner, the status and a redacted excerpt, and tells a request that will never pass (4xx) from one worth retrying (5xx, 429, timeout).
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { JsonHttpClient, multipart } from '@tcds-io/http-client';
|
|
7
|
+
import { Secret } from '@tcds-io/redact';
|
|
8
|
+
|
|
9
|
+
const billing = new JsonHttpClient({
|
|
10
|
+
party: 'billing',
|
|
11
|
+
baseUrl: 'https://api.billing.example/v1',
|
|
12
|
+
headers: { authorization: Secret.from(`Bearer ${key}`) }, // revealed only when the request is sent
|
|
13
|
+
timeoutMs: 10_000,
|
|
14
|
+
retry: (attempt, error) => (attempt < 4 ? 500 * 2 ** attempt : null), // optional; ms to wait, or null to give up
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const { body } = await billing.request<{ id: string }>({ method: 'POST', path: 'invoices', body: { amount: 100 } });
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
| Outcome | Error | `retryable` |
|
|
21
|
+
|---|---|---|
|
|
22
|
+
| 2xx | the parsed body | |
|
|
23
|
+
| 429 | `RateLimitedError`, `retryAfterMs` from `Retry-After` | yes |
|
|
24
|
+
| 408, 425, 5xx, no answer | `ExternalPartyError` | yes |
|
|
25
|
+
| other non-2xx | `RefusedByExternalPartyError` | no |
|
|
26
|
+
|
|
27
|
+
Errors never contain the query string or credentials. The retry hook is only asked about retryable failures, and `sleep` is injectable.
|
|
28
|
+
|
|
29
|
+
## Testing
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { RecordingHttpClient } from '@tcds-io/http-client/testing';
|
|
33
|
+
|
|
34
|
+
const http = new RecordingHttpClient().stub('GET /invoices/1', { body: { id: '1' } }).enqueue({ status: 503 });
|
|
35
|
+
http.calls; // every call, headers and secrets masked
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
It runs the real client over a fake `fetch`, so a stubbed `429` or `400` becomes the same error production throws. Stubs (`'METHOD /path'`) are kept; `enqueue` answers are used once, in order.
|
|
39
|
+
|
|
40
|
+
## Peers
|
|
41
|
+
|
|
42
|
+
`@tcds-io/domain` and `@tcds-io/redact` are peer dependencies: install them yourself so `instanceof` and `Secret` work across the app (ADR-0070).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { JsonHttpClient, loggableHeaders, parseRetryAfter } from './json-http-client.js';
|
|
2
|
+
export type { JsonHttpClientOptions } from './json-http-client.js';
|
|
3
|
+
export { MultipartBody, multipart } from './multipart.js';
|
|
4
|
+
export type { MultipartFile } from './multipart.js';
|
|
5
|
+
export { revealDeep } from './reveal.js';
|
|
6
|
+
export type { HttpClient, HttpMethod, HttpRequest, HttpResponse } from './types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { AppError } from '@tcds-io/domain';
|
|
2
|
+
import { Secret, type Redactor } from '@tcds-io/redact';
|
|
3
|
+
import type { HttpClient, HttpRequest, HttpResponse } from './types.js';
|
|
4
|
+
export type JsonHttpClientOptions = {
|
|
5
|
+
/** Used as the `party` on every error. */
|
|
6
|
+
readonly party: string;
|
|
7
|
+
readonly baseUrl?: string;
|
|
8
|
+
/** Sent on every request. A `Secret` is revealed at send time. */
|
|
9
|
+
readonly headers?: Readonly<Record<string, string | Secret>>;
|
|
10
|
+
/** Default 30 000. */
|
|
11
|
+
readonly timeoutMs?: number;
|
|
12
|
+
/** Default: global `fetch`. */
|
|
13
|
+
readonly fetch?: typeof fetch;
|
|
14
|
+
/** Default: `AbortSignal.timeout`. Inject a controller's signal in tests. */
|
|
15
|
+
readonly timeoutSignal?: (ms: number) => AbortSignal;
|
|
16
|
+
/**
|
|
17
|
+
* After a failed attempt that is not terminal, return the pause in ms before the next one, or null to give up.
|
|
18
|
+
* `attempt` counts failures so far (1 after the first). Same shape as a backoff function; see `@tcds-io/retry`.
|
|
19
|
+
*/
|
|
20
|
+
readonly retry?: (attempt: number, error: AppError) => number | null;
|
|
21
|
+
/** Default: real timers. */
|
|
22
|
+
readonly sleep?: (ms: number) => Promise<void>;
|
|
23
|
+
readonly redactor?: Redactor;
|
|
24
|
+
/** Characters of a failed response's body kept on the error. Default 500. */
|
|
25
|
+
readonly maxExcerpt?: number;
|
|
26
|
+
/** Error codes. Defaults shown. */
|
|
27
|
+
readonly codes?: {
|
|
28
|
+
readonly unreachable?: string;
|
|
29
|
+
readonly failed?: string;
|
|
30
|
+
readonly refused?: string;
|
|
31
|
+
readonly rateLimited?: string;
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
/** `Retry-After` is seconds or an HTTP date. Returns ms, or undefined. */
|
|
35
|
+
export declare const parseRetryAfter: (value: string | null, now?: () => number) => number | undefined;
|
|
36
|
+
/**
|
|
37
|
+
* A JSON `fetch` client for partner APIs.
|
|
38
|
+
*
|
|
39
|
+
* Outcome → error:
|
|
40
|
+
* - 2xx: the parsed body (JSON when the text parses, else the text; empty body is `undefined`).
|
|
41
|
+
* - 429: `RateLimitedError`, with `retryAfterMs` from `Retry-After`.
|
|
42
|
+
* - 408, 425 and 5xx: `ExternalPartyError` (retryable).
|
|
43
|
+
* - any other non-2xx, 4xx in practice: `RefusedByExternalPartyError` (not retryable: the partner will refuse it again).
|
|
44
|
+
* - no answer (network error, timeout): `ExternalPartyError` with code `unreachable` (retryable).
|
|
45
|
+
* Errors carry `party`, `status` and details `{ method, url, bodyExcerpt }`, redacted: no query string, no credentials.
|
|
46
|
+
*/
|
|
47
|
+
export declare class JsonHttpClient implements HttpClient {
|
|
48
|
+
private readonly options;
|
|
49
|
+
private readonly redactor;
|
|
50
|
+
private readonly codes;
|
|
51
|
+
constructor(options: JsonHttpClientOptions);
|
|
52
|
+
request<T = unknown>(request: HttpRequest): Promise<HttpResponse<T>>;
|
|
53
|
+
private attempt;
|
|
54
|
+
private failure;
|
|
55
|
+
private urlOf;
|
|
56
|
+
}
|
|
57
|
+
/** Headers as they may be logged: sensitive names blanked. */
|
|
58
|
+
export declare const loggableHeaders: (headers: Readonly<Record<string, unknown>>) => Record<string, string>;
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { AppError, ExternalPartyError, RateLimitedError, RefusedByExternalPartyError } from '@tcds-io/domain';
|
|
2
|
+
import { createRedactor, redactHeaders, Secret } from '@tcds-io/redact';
|
|
3
|
+
import { MultipartBody } from './multipart.js';
|
|
4
|
+
import { revealDeep } from './reveal.js';
|
|
5
|
+
const DEFAULT_CODES = { unreachable: 'EXTERNAL_PARTY_UNREACHABLE', failed: 'EXTERNAL_PARTY_FAILED', refused: 'EXTERNAL_PARTY_REFUSED', rateLimited: 'EXTERNAL_PARTY_RATE_LIMITED' };
|
|
6
|
+
/** `Retry-After` is seconds or an HTTP date. Returns ms, or undefined. */
|
|
7
|
+
export const parseRetryAfter = (value, now = Date.now) => {
|
|
8
|
+
if (value === null || value.trim() === '') {
|
|
9
|
+
return undefined;
|
|
10
|
+
}
|
|
11
|
+
if (/^\d+$/.test(value.trim())) {
|
|
12
|
+
return Number(value.trim()) * 1000;
|
|
13
|
+
}
|
|
14
|
+
const date = Date.parse(value);
|
|
15
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - now());
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* A JSON `fetch` client for partner APIs.
|
|
19
|
+
*
|
|
20
|
+
* Outcome → error:
|
|
21
|
+
* - 2xx: the parsed body (JSON when the text parses, else the text; empty body is `undefined`).
|
|
22
|
+
* - 429: `RateLimitedError`, with `retryAfterMs` from `Retry-After`.
|
|
23
|
+
* - 408, 425 and 5xx: `ExternalPartyError` (retryable).
|
|
24
|
+
* - any other non-2xx, 4xx in practice: `RefusedByExternalPartyError` (not retryable: the partner will refuse it again).
|
|
25
|
+
* - no answer (network error, timeout): `ExternalPartyError` with code `unreachable` (retryable).
|
|
26
|
+
* Errors carry `party`, `status` and details `{ method, url, bodyExcerpt }`, redacted: no query string, no credentials.
|
|
27
|
+
*/
|
|
28
|
+
export class JsonHttpClient {
|
|
29
|
+
options;
|
|
30
|
+
redactor;
|
|
31
|
+
codes;
|
|
32
|
+
constructor(options) {
|
|
33
|
+
this.options = options;
|
|
34
|
+
this.redactor = options.redactor ?? createRedactor();
|
|
35
|
+
this.codes = { ...DEFAULT_CODES, ...options.codes };
|
|
36
|
+
}
|
|
37
|
+
async request(request) {
|
|
38
|
+
for (let failures = 1;; failures += 1) {
|
|
39
|
+
try {
|
|
40
|
+
return await this.attempt(request);
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (!(error instanceof AppError) || error.retryable === false || this.options.retry === undefined) {
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
const pause = this.options.retry(failures, error);
|
|
47
|
+
if (pause === null) {
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
await (this.options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(pause);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async attempt(request) {
|
|
55
|
+
const method = request.method ?? 'GET';
|
|
56
|
+
const url = this.urlOf(request);
|
|
57
|
+
const logUrl = this.redactor.forLog(url);
|
|
58
|
+
const timeoutMs = request.timeoutMs ?? this.options.timeoutMs ?? 30_000;
|
|
59
|
+
const timeout = (this.options.timeoutSignal ?? ((ms) => AbortSignal.timeout(ms)))(timeoutMs);
|
|
60
|
+
const signal = request.signal !== undefined ? AbortSignal.any([timeout, request.signal]) : timeout;
|
|
61
|
+
const headers = new Headers();
|
|
62
|
+
for (const [name, value] of Object.entries({ ...this.options.headers, ...request.headers })) {
|
|
63
|
+
headers.set(name, value instanceof Secret ? value.reveal() : value);
|
|
64
|
+
}
|
|
65
|
+
let body;
|
|
66
|
+
if (request.body instanceof MultipartBody) {
|
|
67
|
+
body = request.body.toFormData();
|
|
68
|
+
}
|
|
69
|
+
else if (request.body !== undefined) {
|
|
70
|
+
body = JSON.stringify(revealDeep(request.body));
|
|
71
|
+
if (!headers.has('content-type')) {
|
|
72
|
+
headers.set('content-type', 'application/json');
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
let response;
|
|
76
|
+
try {
|
|
77
|
+
response = await (this.options.fetch ?? fetch)(url, { method, headers, signal, ...(body !== undefined ? { body } : {}) });
|
|
78
|
+
}
|
|
79
|
+
catch (cause) {
|
|
80
|
+
throw new ExternalPartyError(this.codes.unreachable, {
|
|
81
|
+
message: `${this.options.party} unreachable: ${method} ${logUrl}`,
|
|
82
|
+
party: this.options.party,
|
|
83
|
+
details: { method, url: logUrl, reason: signal.aborted ? 'timeout-or-abort' : 'network' },
|
|
84
|
+
cause,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
const text = await response.text();
|
|
88
|
+
const responseHeaders = Object.fromEntries(response.headers.entries());
|
|
89
|
+
if (response.ok) {
|
|
90
|
+
return { status: response.status, headers: responseHeaders, body: parseBody(text) };
|
|
91
|
+
}
|
|
92
|
+
throw this.failure(response, text, method, logUrl);
|
|
93
|
+
}
|
|
94
|
+
failure(response, text, method, logUrl) {
|
|
95
|
+
const { party } = this.options;
|
|
96
|
+
const status = response.status;
|
|
97
|
+
const excerpt = this.redactor.forLog(text.slice(0, this.options.maxExcerpt ?? 500));
|
|
98
|
+
const details = { method, url: logUrl, status, bodyExcerpt: excerpt };
|
|
99
|
+
const message = `${party} answered ${status}: ${method} ${logUrl}`;
|
|
100
|
+
if (status === 429) {
|
|
101
|
+
const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'));
|
|
102
|
+
return new RateLimitedError(this.codes.rateLimited, { message, details, ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) });
|
|
103
|
+
}
|
|
104
|
+
if (status === 408 || status === 425 || status >= 500) {
|
|
105
|
+
return new ExternalPartyError(this.codes.failed, { message, details, party, status });
|
|
106
|
+
}
|
|
107
|
+
return new RefusedByExternalPartyError(this.codes.refused, { message, details, party, status });
|
|
108
|
+
}
|
|
109
|
+
urlOf(request) {
|
|
110
|
+
const base = this.options.baseUrl;
|
|
111
|
+
const url = new URL(request.path, base !== undefined ? (base.endsWith('/') ? base : `${base}/`) : undefined);
|
|
112
|
+
for (const [name, value] of Object.entries(request.query ?? {})) {
|
|
113
|
+
if (value !== undefined) {
|
|
114
|
+
url.searchParams.set(name, String(value));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return url.toString();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const parseBody = (text) => {
|
|
121
|
+
if (text === '') {
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
return JSON.parse(text);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return text;
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
/** Headers as they may be logged: sensitive names blanked. */
|
|
132
|
+
export const loggableHeaders = (headers) => redactHeaders(headers);
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Secret } from '@tcds-io/redact';
|
|
2
|
+
export type MultipartFile = {
|
|
3
|
+
/** Form field name. */
|
|
4
|
+
readonly name: string;
|
|
5
|
+
readonly filename: string;
|
|
6
|
+
readonly contentType: string;
|
|
7
|
+
readonly data: Uint8Array;
|
|
8
|
+
};
|
|
9
|
+
/** A `multipart/form-data` body, described, not built: the client builds the `FormData` when it sends. */
|
|
10
|
+
export declare class MultipartBody {
|
|
11
|
+
readonly fields: Readonly<Record<string, string | Secret>>;
|
|
12
|
+
readonly files: readonly MultipartFile[];
|
|
13
|
+
constructor(fields?: Readonly<Record<string, string | Secret>>, files?: readonly MultipartFile[]);
|
|
14
|
+
toFormData(): FormData;
|
|
15
|
+
}
|
|
16
|
+
export declare const multipart: (fields?: Readonly<Record<string, string | Secret>>, files?: readonly MultipartFile[]) => MultipartBody;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Secret as SecretClass } from '@tcds-io/redact';
|
|
2
|
+
/** A `multipart/form-data` body, described, not built: the client builds the `FormData` when it sends. */
|
|
3
|
+
export class MultipartBody {
|
|
4
|
+
fields;
|
|
5
|
+
files;
|
|
6
|
+
constructor(fields = {}, files = []) {
|
|
7
|
+
this.fields = fields;
|
|
8
|
+
this.files = files;
|
|
9
|
+
}
|
|
10
|
+
toFormData() {
|
|
11
|
+
const form = new FormData();
|
|
12
|
+
for (const [name, value] of Object.entries(this.fields)) {
|
|
13
|
+
form.append(name, value instanceof SecretClass ? value.reveal() : value);
|
|
14
|
+
}
|
|
15
|
+
for (const file of this.files) {
|
|
16
|
+
form.append(file.name, new Blob([file.data], { type: file.contentType }), file.filename);
|
|
17
|
+
}
|
|
18
|
+
return form;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export const multipart = (fields = {}, files = []) => new MultipartBody(fields, files);
|
package/dist/reveal.d.ts
ADDED
package/dist/reveal.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Secret } from '@tcds-io/redact';
|
|
2
|
+
/** A deep copy with every `Secret` replaced by its value. Called only on the way out the door. */
|
|
3
|
+
export const revealDeep = (value) => {
|
|
4
|
+
if (value instanceof Secret) {
|
|
5
|
+
return value.reveal();
|
|
6
|
+
}
|
|
7
|
+
if (Array.isArray(value)) {
|
|
8
|
+
return value.map(revealDeep);
|
|
9
|
+
}
|
|
10
|
+
if (typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype) {
|
|
11
|
+
return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, revealDeep(inner)]));
|
|
12
|
+
}
|
|
13
|
+
return value;
|
|
14
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type JsonHttpClientOptions } from './json-http-client.js';
|
|
2
|
+
import type { HttpClient, HttpRequest, HttpResponse } from './types.js';
|
|
3
|
+
export type StubResponse = {
|
|
4
|
+
readonly status?: number;
|
|
5
|
+
readonly body?: unknown;
|
|
6
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
7
|
+
};
|
|
8
|
+
/** A response to answer with, or an error to fail with (a network failure, say). */
|
|
9
|
+
export type Answer = StubResponse | Error | ((call: RecordedCall) => StubResponse | Error);
|
|
10
|
+
export type RecordedCall = {
|
|
11
|
+
readonly method: string;
|
|
12
|
+
readonly path: string;
|
|
13
|
+
readonly query: Readonly<Record<string, string | number | boolean | undefined>>;
|
|
14
|
+
/** Sensitive headers blanked, `Secret` values masked. */
|
|
15
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
16
|
+
/** The body as logged: a `Secret` inside prints `[redacted]`, text goes through the redactor. */
|
|
17
|
+
readonly body: unknown;
|
|
18
|
+
};
|
|
19
|
+
export declare class NoStubbedResponseError extends Error {
|
|
20
|
+
constructor(call: string);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* A test double for an `HttpClient`. It runs the real `JsonHttpClient` over a fake `fetch`, so error mapping (429,
|
|
24
|
+
* 5xx, 4xx, unreachable), retries and timeouts behave exactly like production. Answers come from, in order:
|
|
25
|
+
* a `stub('GET /orders/1', answer)` route (kept until replaced), then the `enqueue(answer)` FIFO (each used once).
|
|
26
|
+
* Nothing left throws `NoStubbedResponseError`.
|
|
27
|
+
*/
|
|
28
|
+
export declare class RecordingHttpClient implements HttpClient {
|
|
29
|
+
readonly calls: RecordedCall[];
|
|
30
|
+
private readonly routes;
|
|
31
|
+
private readonly queue;
|
|
32
|
+
private readonly inner;
|
|
33
|
+
private readonly redactor;
|
|
34
|
+
constructor(options?: Partial<JsonHttpClientOptions>);
|
|
35
|
+
/** `'METHOD /path'` (the path without query). Replaces an earlier stub for the same key. */
|
|
36
|
+
stub(route: string, answer: Answer): this;
|
|
37
|
+
enqueue(...answers: Answer[]): this;
|
|
38
|
+
request<T = unknown>(request: HttpRequest): Promise<HttpResponse<T>>;
|
|
39
|
+
private loggable;
|
|
40
|
+
private answer;
|
|
41
|
+
}
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { createRedactor, redactHeaders } from '@tcds-io/redact';
|
|
2
|
+
import { JsonHttpClient } from './json-http-client.js';
|
|
3
|
+
import { MultipartBody } from './multipart.js';
|
|
4
|
+
export class NoStubbedResponseError extends Error {
|
|
5
|
+
constructor(call) {
|
|
6
|
+
super(`No stubbed response for ${call}: add a stub() or enqueue() before the call`);
|
|
7
|
+
this.name = 'NoStubbedResponseError';
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* A test double for an `HttpClient`. It runs the real `JsonHttpClient` over a fake `fetch`, so error mapping (429,
|
|
12
|
+
* 5xx, 4xx, unreachable), retries and timeouts behave exactly like production. Answers come from, in order:
|
|
13
|
+
* a `stub('GET /orders/1', answer)` route (kept until replaced), then the `enqueue(answer)` FIFO (each used once).
|
|
14
|
+
* Nothing left throws `NoStubbedResponseError`.
|
|
15
|
+
*/
|
|
16
|
+
export class RecordingHttpClient {
|
|
17
|
+
calls = [];
|
|
18
|
+
routes = [];
|
|
19
|
+
queue = [];
|
|
20
|
+
inner;
|
|
21
|
+
redactor;
|
|
22
|
+
constructor(options = {}) {
|
|
23
|
+
this.redactor = options.redactor ?? createRedactor();
|
|
24
|
+
this.inner = new JsonHttpClient({
|
|
25
|
+
party: 'test-partner',
|
|
26
|
+
baseUrl: 'http://partner.test',
|
|
27
|
+
...options,
|
|
28
|
+
fetch: (input, init) => this.answer(String(input), init),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/** `'METHOD /path'` (the path without query). Replaces an earlier stub for the same key. */
|
|
32
|
+
stub(route, answer) {
|
|
33
|
+
const index = this.routes.findIndex((existing) => existing.key === route);
|
|
34
|
+
if (index >= 0) {
|
|
35
|
+
this.routes.splice(index, 1);
|
|
36
|
+
}
|
|
37
|
+
this.routes.push({ key: route, answer });
|
|
38
|
+
return this;
|
|
39
|
+
}
|
|
40
|
+
enqueue(...answers) {
|
|
41
|
+
this.queue.push(...answers);
|
|
42
|
+
return this;
|
|
43
|
+
}
|
|
44
|
+
request(request) {
|
|
45
|
+
this.calls.push({
|
|
46
|
+
method: request.method ?? 'GET',
|
|
47
|
+
path: request.path,
|
|
48
|
+
query: request.query ?? {},
|
|
49
|
+
headers: redactHeaders(request.headers ?? {}),
|
|
50
|
+
body: this.loggable(request.body),
|
|
51
|
+
});
|
|
52
|
+
return this.inner.request(request).catch((error) => {
|
|
53
|
+
// A missing stub is a mistake in the test, not a partner failure: surface it as itself.
|
|
54
|
+
throw error instanceof Error && error.cause instanceof NoStubbedResponseError ? error.cause : error;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
loggable(body) {
|
|
58
|
+
if (body instanceof MultipartBody) {
|
|
59
|
+
return { fields: Object.keys(body.fields), files: body.files.map((file) => file.filename) };
|
|
60
|
+
}
|
|
61
|
+
if (typeof body === 'string') {
|
|
62
|
+
return this.redactor.forLog(body);
|
|
63
|
+
}
|
|
64
|
+
return body === undefined ? undefined : this.redactor.valueForLog(body);
|
|
65
|
+
}
|
|
66
|
+
answer(url, init) {
|
|
67
|
+
const method = init?.method ?? 'GET';
|
|
68
|
+
const path = new URL(url).pathname;
|
|
69
|
+
const key = `${method} ${path}`;
|
|
70
|
+
const route = this.routes.find((candidate) => candidate.key === key);
|
|
71
|
+
const picked = route?.answer ?? this.queue.shift();
|
|
72
|
+
if (picked === undefined) {
|
|
73
|
+
return Promise.reject(new NoStubbedResponseError(key));
|
|
74
|
+
}
|
|
75
|
+
const last = this.calls.at(-1);
|
|
76
|
+
const resolved = typeof picked === 'function' ? picked(last ?? { method, path, query: {}, headers: {}, body: undefined }) : picked;
|
|
77
|
+
if (resolved instanceof Error) {
|
|
78
|
+
return Promise.reject(resolved);
|
|
79
|
+
}
|
|
80
|
+
const status = resolved.status ?? 200;
|
|
81
|
+
const text = resolved.body === undefined ? '' : typeof resolved.body === 'string' ? resolved.body : JSON.stringify(resolved.body);
|
|
82
|
+
return Promise.resolve(new Response(status === 204 ? null : text, { status, headers: resolved.headers ?? {} }));
|
|
83
|
+
}
|
|
84
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Secret } from '@tcds-io/redact';
|
|
2
|
+
import type { MultipartBody } from './multipart.js';
|
|
3
|
+
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
4
|
+
export type HttpRequest = {
|
|
5
|
+
readonly method?: HttpMethod;
|
|
6
|
+
/** Relative to the client's `baseUrl`, or absolute. */
|
|
7
|
+
readonly path: string;
|
|
8
|
+
readonly query?: Readonly<Record<string, string | number | boolean | undefined>>;
|
|
9
|
+
/** A `Secret` value is revealed only when the request is sent. */
|
|
10
|
+
readonly headers?: Readonly<Record<string, string | Secret>>;
|
|
11
|
+
/** A plain value is sent as JSON (any `Secret` inside is revealed at send time); a `MultipartBody` as a form. */
|
|
12
|
+
readonly body?: unknown;
|
|
13
|
+
readonly timeoutMs?: number;
|
|
14
|
+
readonly signal?: AbortSignal;
|
|
15
|
+
};
|
|
16
|
+
export type HttpResponse<T = unknown> = {
|
|
17
|
+
readonly status: number;
|
|
18
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
19
|
+
readonly body: T;
|
|
20
|
+
};
|
|
21
|
+
export interface HttpClient {
|
|
22
|
+
/** Resolves on a 2xx. Anything else throws an `@tcds-io/domain` error carrying the status and a redacted excerpt. */
|
|
23
|
+
request<T = unknown>(request: HttpRequest): Promise<HttpResponse<T>>;
|
|
24
|
+
}
|
|
25
|
+
export type { MultipartBody };
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tcds-io/http-client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "JSON fetch client that throws external-party errors, with a recording test double that redacts secrets.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/tcds-io/ts-platform.git",
|
|
11
|
+
"directory": "packages/http-client"
|
|
12
|
+
},
|
|
13
|
+
"publishConfig": {
|
|
14
|
+
"access": "public",
|
|
15
|
+
"registry": "https://registry.npmjs.org"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"import": "./dist/index.js"
|
|
24
|
+
},
|
|
25
|
+
"./testing": {
|
|
26
|
+
"types": "./dist/testing.d.ts",
|
|
27
|
+
"import": "./dist/testing.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/node": "^22.10.2",
|
|
32
|
+
"typescript": "^5.7.2",
|
|
33
|
+
"vitest": "^2.1.8",
|
|
34
|
+
"@tcds-io/domain": "^0.1.0",
|
|
35
|
+
"@tcds-io/redact": "^0.1.0"
|
|
36
|
+
},
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=22"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"@tcds-io/domain": "~0.1.0",
|
|
42
|
+
"@tcds-io/redact": "~0.1.0"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
|
|
46
|
+
"check:types": "tsc --noEmit -p .",
|
|
47
|
+
"test": "vitest run"
|
|
48
|
+
}
|
|
6
49
|
}
|