@backendkit-labs/http-client 0.1.0 → 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.
Files changed (3) hide show
  1. package/LICENSE +184 -0
  2. package/README.md +328 -328
  3. package/package.json +67 -40
package/LICENSE ADDED
@@ -0,0 +1,184 @@
1
+  Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and the Work's derivative works.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as
57
+ "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and subsequently
61
+ incorporated within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contribution embodied within the Work constitutes direct or contributory
82
+ patent infringement, then any patent licenses granted to You under
83
+ this License for that Work shall terminate as of the date such
84
+ litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the License.
117
+
118
+ You may add Your own license statement for Your modifications and
119
+ may provide additional grant of rights to use, copy, modify, and
120
+ distribute Your modifications, or for such Derivative Works as a
121
+ whole, subject to the terms and conditions of this License.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any warranties or conditions
141
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
142
+ PARTICULAR PURPOSE. You are solely responsible for determining the
143
+ appropriateness of using or reproducing the Work and assume any
144
+ risks associated with Your exercise of permissions under this License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory,
147
+ whether in tort (including negligence), contract, or otherwise,
148
+ unless required by applicable law (such as deliberate and grossly
149
+ negligent acts) or agreed to in writing, shall any Contributor be
150
+ liable to You for damages, including any direct, indirect, special,
151
+ incidental, or exemplary damages of any character arising as a
152
+ result of this License or out of the use or inability to use the
153
+ Work (including but not limited to damages for loss of goodwill,
154
+ work stoppage, computer failure or malfunction, or all other
155
+ commercial damages or losses), even if such Contributor has been
156
+ advised of the possibility of such damages.
157
+
158
+ 9. Accepting Warranty or Additional Liability. While redistributing
159
+ the Work or Derivative Works thereof, You may choose to offer,
160
+ and charge a fee for, acceptance of support, warranty, indemnity,
161
+ or other liability obligations and/or rights consistent with this
162
+ License. However, in accepting such obligations, You may act only
163
+ on Your own behalf and on Your sole responsibility, not on behalf
164
+ of any other Contributor, and only if You agree to indemnify,
165
+ defend, and hold each Contributor harmless for any liability
166
+ incurred by, or claims asserted against, such Contributor by reason
167
+ of your accepting any such warranty or additional liability.
168
+
169
+ END OF TERMS AND CONDITIONS
170
+
171
+ Copyright 2024-2026 Mairon José Cuello Martí­nez
172
+
173
+ Licensed under the Apache License, Version 2.0 (the "License");
174
+ you may not use this file except in compliance with the License.
175
+ You may obtain a copy of the License at
176
+
177
+ http://www.apache.org/licenses/LICENSE-2.0
178
+
179
+ Unless required by applicable law or agreed to in writing, software
180
+ distributed under the License is distributed on an "AS IS" BASIS,
181
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
182
+ See the License for the specific language governing permissions and
183
+ limitations under the License.
184
+
package/README.md CHANGED
@@ -1,328 +1,328 @@
1
- # @backendkit-labs/http-client
2
-
3
- [![npm version](https://img.shields.io/npm/v/@backendkit-labs/http-client?style=flat-square&color=cb3837)](https://www.npmjs.com/package/@backendkit-labs/http-client)
4
- [![CI](https://img.shields.io/github/actions/workflow/status/backendkit-dev/backendkit-monorepo/ci.yml?style=flat-square&label=CI)](https://github.com/backendkit-dev/backendkit-monorepo/actions/workflows/ci.yml)
5
- [![License](https://img.shields.io/npm/l/@backendkit-labs/http-client?style=flat-square)](LICENSE)
6
- [![Node](https://img.shields.io/node/v/@backendkit-labs/http-client?style=flat-square)](package.json)
7
-
8
- > Production-grade HTTP client for Node.js — built on axios with circuit breaker, retry with exponential backoff, typed `Result<T, E>` responses, request cancellation, pre-request pipeline middleware, and optional NestJS DI integration.
9
-
10
- Every method returns `Result<HttpResponse<T>, HttpClientError>` — no try/catch needed, no unhandled rejections, always typed.
11
-
12
- ---
13
-
14
- ## Installation
15
-
16
- ```bash
17
- npm install @backendkit-labs/http-client axios
18
- ```
19
-
20
- NestJS peer dependencies (only for the `/nestjs` subpath):
21
-
22
- ```bash
23
- npm install @nestjs/common @nestjs/core rxjs
24
- ```
25
-
26
- ---
27
-
28
- ## TypeScript Configuration
29
-
30
- ### Subpath exports (`/nestjs`)
31
-
32
- This package uses the `exports` field in `package.json` to expose the `/nestjs` subpath. TypeScript's ability to resolve it depends on the `moduleResolution` setting in your `tsconfig.json`.
33
-
34
- **Modern resolution (recommended) — no extra config needed:**
35
-
36
- ```json
37
- {
38
- "compilerOptions": {
39
- "moduleResolution": "bundler"
40
- }
41
- }
42
- ```
43
-
44
- `"bundler"`, `"node16"`, and `"nodenext"` all understand the `exports` field natively.
45
-
46
- **Legacy resolution (`"node"`) — add `paths` aliases:**
47
-
48
- ```json
49
- {
50
- "compilerOptions": {
51
- "moduleResolution": "node",
52
- "paths": {
53
- "@backendkit-labs/http-client/nestjs": [
54
- "./node_modules/@backendkit-labs/http-client/dist/nestjs/index.d.ts"
55
- ]
56
- }
57
- }
58
- }
59
- ```
60
-
61
- **NestJS decorator support:**
62
-
63
- ```json
64
- {
65
- "compilerOptions": {
66
- "experimentalDecorators": true,
67
- "emitDecoratorMetadata": true
68
- }
69
- }
70
- ```
71
-
72
- And in your `main.ts`, before anything else:
73
-
74
- ```typescript
75
- import 'reflect-metadata';
76
- ```
77
-
78
- ---
79
-
80
- ## Quick Start
81
-
82
- ```typescript
83
- import { HttpClient } from '@backendkit-labs/http-client';
84
-
85
- const client = new HttpClient({
86
- baseURL: 'https://api.example.com',
87
- timeout: 5_000,
88
- });
89
-
90
- // All methods return Result<HttpResponse<T>, HttpClientError>
91
- const result = await client.get<User[]>('/users');
92
-
93
- if (result.ok) {
94
- console.log(result.value.data); // User[]
95
- console.log(result.value.status); // 200
96
- } else {
97
- console.error(result.error.type); // 'http' | 'network' | 'timeout' | 'cancelled' | 'circuit-open'
98
- console.error(result.error.status); // 404, 500, etc. (for 'http' type)
99
- }
100
- ```
101
-
102
- ---
103
-
104
- ## Configuration
105
-
106
- ```typescript
107
- const client = new HttpClient({
108
- baseURL: 'https://api.example.com',
109
- timeout: 10_000, // default: 10 000 ms
110
- headers: { 'X-API-Key': 'secret' },
111
-
112
- // Retry with exponential backoff + jitter
113
- retry: {
114
- attempts: 3, // retries after first failure
115
- delayMs: 100,
116
- maxDelayMs: 5_000,
117
- jitter: true,
118
- shouldRetry: (err) => err.type === 'network' || err.type === 'timeout',
119
- },
120
-
121
- // Circuit breaker
122
- circuitBreaker: {
123
- failureThreshold: 50, // % of calls that must fail to open the circuit
124
- minimumCalls: 5, // minimum calls before evaluating thresholds
125
- slidingWindowSize: 10,
126
- openTimeoutMs: 30_000,
127
- },
128
-
129
- // Pre-request middleware steps
130
- steps: [authStep, correlationIdStep],
131
- });
132
- ```
133
-
134
- ---
135
-
136
- ## HTTP Methods
137
-
138
- All methods accept an optional `RequestConfig`:
139
-
140
- ```typescript
141
- interface RequestConfig {
142
- headers?: Record<string, string>;
143
- params?: Record<string, unknown>; // query string parameters
144
- timeout?: number; // per-request override
145
- cancelKey?: string; // key to cancel this request
146
- correlationId?: string;
147
- }
148
- ```
149
-
150
- ```typescript
151
- client.get<T>(url, config?)
152
- client.post<T>(url, data?, config?)
153
- client.put<T>(url, data?, config?)
154
- client.patch<T>(url, data?, config?)
155
- client.delete<T>(url, config?)
156
- ```
157
-
158
- ---
159
-
160
- ## Error Types
161
-
162
- ```typescript
163
- type HttpErrorType = 'http' | 'network' | 'timeout' | 'cancelled' | 'circuit-open';
164
-
165
- interface HttpClientError {
166
- type: HttpErrorType;
167
- message: string;
168
- status?: number; // only for 'http'
169
- data?: unknown; // response body, only for 'http'
170
- cause?: unknown; // original axios error
171
- }
172
- ```
173
-
174
- ---
175
-
176
- ## Request Cancellation
177
-
178
- Register a `cancelKey` on the request and cancel by key at any time:
179
-
180
- ```typescript
181
- const promise = client.get('/long-poll', { cancelKey: 'my-poll' });
182
-
183
- // Cancel a specific request
184
- client.cancelRequest('my-poll');
185
-
186
- // Cancel all in-flight requests
187
- client.cancelAll();
188
-
189
- const result = await promise;
190
- if (!result.ok && result.error.type === 'cancelled') {
191
- // handle cancellation
192
- }
193
- ```
194
-
195
- ---
196
-
197
- ## Pipeline Middleware
198
-
199
- Pre-request middleware steps transform the `HttpCtx` before each request. Steps are powered by `@backendkit-labs/pipeline`.
200
-
201
- ```typescript
202
- import type { PipelineStep, StepResult } from '@backendkit-labs/pipeline';
203
- import { Ok } from '@backendkit-labs/pipeline';
204
- import type { HttpCtx, HttpClientError } from '@backendkit-labs/http-client';
205
-
206
- const authStep: PipelineStep<HttpCtx, HttpClientError> = {
207
- stepName: 'auth',
208
- async handle(ctx): Promise<StepResult<HttpCtx, HttpClientError>> {
209
- const token = await tokenStore.get();
210
- return Ok({ ...ctx, headers: { ...ctx.headers, Authorization: `Bearer ${token}` } });
211
- },
212
- };
213
-
214
- const client = new HttpClient({ steps: [authStep] });
215
- ```
216
-
217
- A step can abort the request by returning `Err(...)`:
218
-
219
- ```typescript
220
- import { Err } from '@backendkit-labs/pipeline';
221
-
222
- const rateLimitStep: PipelineStep<HttpCtx, HttpClientError> = {
223
- stepName: 'rate-limit',
224
- async handle(ctx): Promise<StepResult<HttpCtx, HttpClientError>> {
225
- if (await rateLimiter.isExceeded()) {
226
- return Err({ type: 'network', message: 'Rate limit exceeded' });
227
- }
228
- return Ok(ctx);
229
- },
230
- };
231
- ```
232
-
233
- ---
234
-
235
- ## Observability
236
-
237
- ```typescript
238
- // Snapshot of lifetime counters
239
- client.getMetrics();
240
- // → { requests, success, failed, cancelled, circuitOpen, retried }
241
-
242
- // Circuit breaker state and counters
243
- client.getCircuitBreakerState(); // 'closed' | 'open' | 'half_open' | undefined
244
- client.getCircuitBreakerMetrics(); // detailed metrics or undefined
245
- ```
246
-
247
- ---
248
-
249
- ## NestJS Integration
250
-
251
- ### Module registration
252
-
253
- ```typescript
254
- // Define typed injection tokens
255
- export const PRIMARY_API = defineHttpClient('primary-api');
256
- export const PAYMENTS_API = defineHttpClient('payments-api');
257
- ```
258
-
259
- ```typescript
260
- import { HttpClientModule } from '@backendkit-labs/http-client/nestjs';
261
- import { PRIMARY_API, PAYMENTS_API } from './tokens';
262
-
263
- @Module({
264
- imports: [
265
- HttpClientModule.forRoot({
266
- clients: [
267
- { token: PRIMARY_API, config: { baseURL: 'https://api.example.com', retry: { attempts: 3, delayMs: 100 } } },
268
- { token: PAYMENTS_API, config: { baseURL: 'https://payments.example.com', circuitBreaker: { failureThreshold: 40, minimumCalls: 3 } } },
269
- ],
270
- }),
271
- ],
272
- })
273
- export class AppModule {}
274
- ```
275
-
276
- ### Injection
277
-
278
- ```typescript
279
- import { InjectHttpClient } from '@backendkit-labs/http-client/nestjs';
280
- import { PRIMARY_API } from './tokens';
281
-
282
- @Injectable()
283
- export class UserService {
284
- constructor(
285
- @InjectHttpClient(PRIMARY_API) private readonly http: HttpClient,
286
- ) {}
287
-
288
- async getUsers(): Promise<User[]> {
289
- const result = await this.http.get<User[]>('/users');
290
- if (!result.ok) throw new Error(result.error.message);
291
- return result.value.data;
292
- }
293
- }
294
- ```
295
-
296
- ### Async module registration
297
-
298
- ```typescript
299
- HttpClientModule.forRootAsync({
300
- imports: [ConfigModule],
301
- inject: [ConfigService],
302
- useFactory: (config: ConfigService) => ({
303
- clients: [{
304
- token: PRIMARY_API,
305
- config: { baseURL: config.get('API_URL'), timeout: config.get('API_TIMEOUT') },
306
- }],
307
- }),
308
- }),
309
- ```
310
-
311
- ---
312
-
313
- ## Named Clients
314
-
315
- ```typescript
316
- import { defineHttpClient, HttpClientToken } from '@backendkit-labs/http-client';
317
-
318
- export const GITHUB_API: HttpClientToken = defineHttpClient('github-api');
319
-
320
- // Provides the token's symbol as the NestJS DI token:
321
- // Inject with @InjectHttpClient(GITHUB_API)
322
- ```
323
-
324
- ---
325
-
326
- ## License
327
-
328
- MIT
1
+ # @backendkit-labs/http-client
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@backendkit-labs/http-client?style=flat-square&color=cb3837)](https://www.npmjs.com/package/@backendkit-labs/http-client)
4
+ [![CI](https://img.shields.io/github/actions/workflow/status/backendkit-dev/backendkit-monorepo/ci.yml?style=flat-square&label=CI)](https://github.com/backendkit-dev/backendkit-monorepo/actions/workflows/ci.yml)
5
+ [![License](https://img.shields.io/npm/l/@backendkit-labs/http-client?style=flat-square)](LICENSE)
6
+ [![Node](https://img.shields.io/node/v/@backendkit-labs/http-client?style=flat-square)](package.json)
7
+
8
+ > Production-grade HTTP client for Node.js — built on axios with circuit breaker, retry with exponential backoff, typed `Result<T, E>` responses, request cancellation, pre-request pipeline middleware, and optional NestJS DI integration.
9
+
10
+ Every method returns `Result<HttpResponse<T>, HttpClientError>` — no try/catch needed, no unhandled rejections, always typed.
11
+
12
+ ---
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @backendkit-labs/http-client axios
18
+ ```
19
+
20
+ NestJS peer dependencies (only for the `/nestjs` subpath):
21
+
22
+ ```bash
23
+ npm install @nestjs/common @nestjs/core rxjs
24
+ ```
25
+
26
+ ---
27
+
28
+ ## TypeScript Configuration
29
+
30
+ ### Subpath exports (`/nestjs`)
31
+
32
+ This package uses the `exports` field in `package.json` to expose the `/nestjs` subpath. TypeScript's ability to resolve it depends on the `moduleResolution` setting in your `tsconfig.json`.
33
+
34
+ **Modern resolution (recommended) — no extra config needed:**
35
+
36
+ ```json
37
+ {
38
+ "compilerOptions": {
39
+ "moduleResolution": "bundler"
40
+ }
41
+ }
42
+ ```
43
+
44
+ `"bundler"`, `"node16"`, and `"nodenext"` all understand the `exports` field natively.
45
+
46
+ **Legacy resolution (`"node"`) — add `paths` aliases:**
47
+
48
+ ```json
49
+ {
50
+ "compilerOptions": {
51
+ "moduleResolution": "node",
52
+ "paths": {
53
+ "@backendkit-labs/http-client/nestjs": [
54
+ "./node_modules/@backendkit-labs/http-client/dist/nestjs/index.d.ts"
55
+ ]
56
+ }
57
+ }
58
+ }
59
+ ```
60
+
61
+ **NestJS decorator support:**
62
+
63
+ ```json
64
+ {
65
+ "compilerOptions": {
66
+ "experimentalDecorators": true,
67
+ "emitDecoratorMetadata": true
68
+ }
69
+ }
70
+ ```
71
+
72
+ And in your `main.ts`, before anything else:
73
+
74
+ ```typescript
75
+ import 'reflect-metadata';
76
+ ```
77
+
78
+ ---
79
+
80
+ ## Quick Start
81
+
82
+ ```typescript
83
+ import { HttpClient } from '@backendkit-labs/http-client';
84
+
85
+ const client = new HttpClient({
86
+ baseURL: 'https://api.example.com',
87
+ timeout: 5_000,
88
+ });
89
+
90
+ // All methods return Result<HttpResponse<T>, HttpClientError>
91
+ const result = await client.get<User[]>('/users');
92
+
93
+ if (result.ok) {
94
+ console.log(result.value.data); // User[]
95
+ console.log(result.value.status); // 200
96
+ } else {
97
+ console.error(result.error.type); // 'http' | 'network' | 'timeout' | 'cancelled' | 'circuit-open'
98
+ console.error(result.error.status); // 404, 500, etc. (for 'http' type)
99
+ }
100
+ ```
101
+
102
+ ---
103
+
104
+ ## Configuration
105
+
106
+ ```typescript
107
+ const client = new HttpClient({
108
+ baseURL: 'https://api.example.com',
109
+ timeout: 10_000, // default: 10 000 ms
110
+ headers: { 'X-API-Key': 'secret' },
111
+
112
+ // Retry with exponential backoff + jitter
113
+ retry: {
114
+ attempts: 3, // retries after first failure
115
+ delayMs: 100,
116
+ maxDelayMs: 5_000,
117
+ jitter: true,
118
+ shouldRetry: (err) => err.type === 'network' || err.type === 'timeout',
119
+ },
120
+
121
+ // Circuit breaker
122
+ circuitBreaker: {
123
+ failureThreshold: 50, // % of calls that must fail to open the circuit
124
+ minimumCalls: 5, // minimum calls before evaluating thresholds
125
+ slidingWindowSize: 10,
126
+ openTimeoutMs: 30_000,
127
+ },
128
+
129
+ // Pre-request middleware steps
130
+ steps: [authStep, correlationIdStep],
131
+ });
132
+ ```
133
+
134
+ ---
135
+
136
+ ## HTTP Methods
137
+
138
+ All methods accept an optional `RequestConfig`:
139
+
140
+ ```typescript
141
+ interface RequestConfig {
142
+ headers?: Record<string, string>;
143
+ params?: Record<string, unknown>; // query string parameters
144
+ timeout?: number; // per-request override
145
+ cancelKey?: string; // key to cancel this request
146
+ correlationId?: string;
147
+ }
148
+ ```
149
+
150
+ ```typescript
151
+ client.get<T>(url, config?)
152
+ client.post<T>(url, data?, config?)
153
+ client.put<T>(url, data?, config?)
154
+ client.patch<T>(url, data?, config?)
155
+ client.delete<T>(url, config?)
156
+ ```
157
+
158
+ ---
159
+
160
+ ## Error Types
161
+
162
+ ```typescript
163
+ type HttpErrorType = 'http' | 'network' | 'timeout' | 'cancelled' | 'circuit-open';
164
+
165
+ interface HttpClientError {
166
+ type: HttpErrorType;
167
+ message: string;
168
+ status?: number; // only for 'http'
169
+ data?: unknown; // response body, only for 'http'
170
+ cause?: unknown; // original axios error
171
+ }
172
+ ```
173
+
174
+ ---
175
+
176
+ ## Request Cancellation
177
+
178
+ Register a `cancelKey` on the request and cancel by key at any time:
179
+
180
+ ```typescript
181
+ const promise = client.get('/long-poll', { cancelKey: 'my-poll' });
182
+
183
+ // Cancel a specific request
184
+ client.cancelRequest('my-poll');
185
+
186
+ // Cancel all in-flight requests
187
+ client.cancelAll();
188
+
189
+ const result = await promise;
190
+ if (!result.ok && result.error.type === 'cancelled') {
191
+ // handle cancellation
192
+ }
193
+ ```
194
+
195
+ ---
196
+
197
+ ## Pipeline Middleware
198
+
199
+ Pre-request middleware steps transform the `HttpCtx` before each request. Steps are powered by `@backendkit-labs/pipeline`.
200
+
201
+ ```typescript
202
+ import type { PipelineStep, StepResult } from '@backendkit-labs/pipeline';
203
+ import { Ok } from '@backendkit-labs/pipeline';
204
+ import type { HttpCtx, HttpClientError } from '@backendkit-labs/http-client';
205
+
206
+ const authStep: PipelineStep<HttpCtx, HttpClientError> = {
207
+ stepName: 'auth',
208
+ async handle(ctx): Promise<StepResult<HttpCtx, HttpClientError>> {
209
+ const token = await tokenStore.get();
210
+ return Ok({ ...ctx, headers: { ...ctx.headers, Authorization: `Bearer ${token}` } });
211
+ },
212
+ };
213
+
214
+ const client = new HttpClient({ steps: [authStep] });
215
+ ```
216
+
217
+ A step can abort the request by returning `Err(...)`:
218
+
219
+ ```typescript
220
+ import { Err } from '@backendkit-labs/pipeline';
221
+
222
+ const rateLimitStep: PipelineStep<HttpCtx, HttpClientError> = {
223
+ stepName: 'rate-limit',
224
+ async handle(ctx): Promise<StepResult<HttpCtx, HttpClientError>> {
225
+ if (await rateLimiter.isExceeded()) {
226
+ return Err({ type: 'network', message: 'Rate limit exceeded' });
227
+ }
228
+ return Ok(ctx);
229
+ },
230
+ };
231
+ ```
232
+
233
+ ---
234
+
235
+ ## Observability
236
+
237
+ ```typescript
238
+ // Snapshot of lifetime counters
239
+ client.getMetrics();
240
+ // → { requests, success, failed, cancelled, circuitOpen, retried }
241
+
242
+ // Circuit breaker state and counters
243
+ client.getCircuitBreakerState(); // 'closed' | 'open' | 'half_open' | undefined
244
+ client.getCircuitBreakerMetrics(); // detailed metrics or undefined
245
+ ```
246
+
247
+ ---
248
+
249
+ ## NestJS Integration
250
+
251
+ ### Module registration
252
+
253
+ ```typescript
254
+ // Define typed injection tokens
255
+ export const PRIMARY_API = defineHttpClient('primary-api');
256
+ export const PAYMENTS_API = defineHttpClient('payments-api');
257
+ ```
258
+
259
+ ```typescript
260
+ import { HttpClientModule } from '@backendkit-labs/http-client/nestjs';
261
+ import { PRIMARY_API, PAYMENTS_API } from './tokens';
262
+
263
+ @Module({
264
+ imports: [
265
+ HttpClientModule.forRoot({
266
+ clients: [
267
+ { token: PRIMARY_API, config: { baseURL: 'https://api.example.com', retry: { attempts: 3, delayMs: 100 } } },
268
+ { token: PAYMENTS_API, config: { baseURL: 'https://payments.example.com', circuitBreaker: { failureThreshold: 40, minimumCalls: 3 } } },
269
+ ],
270
+ }),
271
+ ],
272
+ })
273
+ export class AppModule {}
274
+ ```
275
+
276
+ ### Injection
277
+
278
+ ```typescript
279
+ import { InjectHttpClient } from '@backendkit-labs/http-client/nestjs';
280
+ import { PRIMARY_API } from './tokens';
281
+
282
+ @Injectable()
283
+ export class UserService {
284
+ constructor(
285
+ @InjectHttpClient(PRIMARY_API) private readonly http: HttpClient,
286
+ ) {}
287
+
288
+ async getUsers(): Promise<User[]> {
289
+ const result = await this.http.get<User[]>('/users');
290
+ if (!result.ok) throw new Error(result.error.message);
291
+ return result.value.data;
292
+ }
293
+ }
294
+ ```
295
+
296
+ ### Async module registration
297
+
298
+ ```typescript
299
+ HttpClientModule.forRootAsync({
300
+ imports: [ConfigModule],
301
+ inject: [ConfigService],
302
+ useFactory: (config: ConfigService) => ({
303
+ clients: [{
304
+ token: PRIMARY_API,
305
+ config: { baseURL: config.get('API_URL'), timeout: config.get('API_TIMEOUT') },
306
+ }],
307
+ }),
308
+ }),
309
+ ```
310
+
311
+ ---
312
+
313
+ ## Named Clients
314
+
315
+ ```typescript
316
+ import { defineHttpClient, HttpClientToken } from '@backendkit-labs/http-client';
317
+
318
+ export const GITHUB_API: HttpClientToken = defineHttpClient('github-api');
319
+
320
+ // Provides the token's symbol as the NestJS DI token:
321
+ // Inject with @InjectHttpClient(GITHUB_API)
322
+ ```
323
+
324
+ ---
325
+
326
+ ## License
327
+
328
+ Apache-2.0
package/package.json CHANGED
@@ -1,79 +1,106 @@
1
1
  {
2
2
  "name": "@backendkit-labs/http-client",
3
- "version": "0.1.0",
4
- "description": "Production-grade HTTP client for Node.js — built on axios with circuit breaker, retry with backoff, request cancellation, typed Result responses, pipeline middleware, and optional NestJS integration",
3
+ "version": "0.1.1",
4
+ "license": "Apache-2.0",
5
+ "author": {
6
+ "name": "BackendKit Labs",
7
+ "email": "backendkit.dev@gmail.com"
8
+ },
9
+ "description": "Production-grade HTTP client for Node.js — built on axios with circuit breaker, retry with backoff, request cancellation, typed Result responses, pipeline middleware, and optional NestJS integration",
5
10
  "type": "module",
6
11
  "main": "./dist/index.cjs",
7
12
  "module": "./dist/index.js",
8
13
  "types": "./dist/index.d.ts",
9
14
  "exports": {
10
15
  ".": {
11
- "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js",
13
18
  "require": "./dist/index.cjs"
14
19
  },
15
20
  "./nestjs": {
16
- "types": "./dist/nestjs/index.d.ts",
17
- "import": "./dist/nestjs/index.js",
21
+ "types": "./dist/nestjs/index.d.ts",
22
+ "import": "./dist/nestjs/index.js",
18
23
  "require": "./dist/nestjs/index.cjs"
19
24
  }
20
25
  },
21
- "files": ["dist", "README.md", "LICENSE"],
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
22
31
  "scripts": {
23
- "build": "tsup",
24
- "dev": "tsup --watch",
25
- "test": "vitest run",
26
- "test:watch": "vitest",
27
- "test:coverage": "vitest run --coverage",
28
- "typecheck": "tsc --noEmit",
29
- "lint": "eslint src/",
32
+ "build": "tsup",
33
+ "dev": "tsup --watch",
34
+ "test": "vitest run",
35
+ "test:watch": "vitest",
36
+ "test:coverage": "vitest run --coverage",
37
+ "typecheck": "tsc --noEmit",
38
+ "lint": "eslint src/",
30
39
  "prepublishOnly": "npm run build && npm run test && npm run lint"
31
40
  },
32
41
  "keywords": [
33
- "http", "axios", "circuit-breaker", "retry", "result",
34
- "pipeline", "cancel", "nestjs", "node", "typescript"
42
+ "http",
43
+ "axios",
44
+ "circuit-breaker",
45
+ "retry",
46
+ "result",
47
+ "pipeline",
48
+ "cancel",
49
+ "nestjs",
50
+ "node",
51
+ "typescript"
35
52
  ],
36
- "author": "Mairon José Cuello Martínez",
37
- "license": "MIT",
38
53
  "homepage": "https://github.com/backendkit-dev/backendkit-monorepo/tree/master/packages/http-client#readme",
39
54
  "repository": {
40
55
  "type": "git",
41
56
  "url": "git+https://github.com/backendkit-dev/backendkit-monorepo.git",
42
57
  "directory": "packages/http-client"
43
58
  },
44
- "bugs": { "url": "https://github.com/backendkit-dev/backendkit-monorepo/issues" },
45
- "publishConfig": { "access": "public" },
59
+ "bugs": {
60
+ "url": "https://github.com/backendkit-dev/backendkit-monorepo/issues"
61
+ },
62
+ "publishConfig": {
63
+ "access": "public"
64
+ },
46
65
  "sideEffects": false,
47
- "engines": { "node": ">=18" },
66
+ "engines": {
67
+ "node": ">=18"
68
+ },
48
69
  "dependencies": {
49
70
  "@backendkit-labs/circuit-breaker": "*",
50
- "@backendkit-labs/pipeline": "*",
51
- "@backendkit-labs/result": "*"
71
+ "@backendkit-labs/pipeline": "*",
72
+ "@backendkit-labs/result": "*"
52
73
  },
53
74
  "peerDependencies": {
54
75
  "@nestjs/common": ">=10.0.0",
55
- "@nestjs/core": ">=10.0.0",
56
- "axios": ">=1.0.0",
57
- "rxjs": ">=7.0.0"
76
+ "@nestjs/core": ">=10.0.0",
77
+ "axios": ">=1.0.0",
78
+ "rxjs": ">=7.0.0"
58
79
  },
59
80
  "peerDependenciesMeta": {
60
- "@nestjs/common": { "optional": true },
61
- "@nestjs/core": { "optional": true },
62
- "rxjs": { "optional": true }
81
+ "@nestjs/common": {
82
+ "optional": true
83
+ },
84
+ "@nestjs/core": {
85
+ "optional": true
86
+ },
87
+ "rxjs": {
88
+ "optional": true
89
+ }
63
90
  },
64
91
  "devDependencies": {
65
- "@eslint/js": "^9.39.4",
66
- "@nestjs/common": "^10.0.0",
67
- "@nestjs/core": "^10.0.0",
68
- "@types/node": "^22.0.0",
69
- "axios": "^1.7.0",
92
+ "@eslint/js": "^9.39.4",
93
+ "@nestjs/common": "^10.0.0",
94
+ "@nestjs/core": "^10.0.0",
95
+ "@types/node": "^22.0.0",
96
+ "axios": "^1.7.0",
70
97
  "axios-mock-adapter": "^2.1.0",
71
- "eslint": "^9.0.0",
72
- "reflect-metadata": "^0.2.0",
73
- "rxjs": "^7.8.0",
74
- "tsup": "^8.0.0",
75
- "typescript": "^5.5.0",
98
+ "eslint": "^9.0.0",
99
+ "reflect-metadata": "^0.2.0",
100
+ "rxjs": "^7.8.0",
101
+ "tsup": "^8.0.0",
102
+ "typescript": "^5.5.0",
76
103
  "typescript-eslint": "^8.59.3",
77
- "vitest": "^2.0.0"
104
+ "vitest": "^2.0.0"
78
105
  }
79
106
  }