Skip to content

Commit d4968ac

Browse files
committed
adding examples to enabled more collaboration
1 parent 063ed06 commit d4968ac

File tree

3 files changed

+48
-1
lines changed

3 files changed

+48
-1
lines changed

examples/failing.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import HttpClient, { HttpClientError } from '../lib/http-client.js';
2+
3+
/**
4+
* Example of the circuit breaker opening on a failing request.
5+
*/
6+
const client = new HttpClient();
7+
try {
8+
await client.request({
9+
origin: 'http://localhost:9099',
10+
path: '/',
11+
method: 'GET',
12+
});
13+
} catch (_) {
14+
// Mute the first one, next request should hit an open breaker
15+
}
16+
17+
try {
18+
await client.request({
19+
origin: 'http://localhost:9099',
20+
path: '/',
21+
method: 'GET',
22+
});
23+
} catch (err) {
24+
if (err instanceof HttpClientError) {
25+
if (err.code === HttpClientError.ServerDown) {
26+
console.error('Server unavailable..');
27+
}
28+
}
29+
}

examples/success.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import HttpClient from '../lib/http-client.js';
2+
3+
const client = new HttpClient();
4+
const response = await client.request({
5+
origin: 'https://www.google.com',
6+
path: '/',
7+
method: 'GET',
8+
maxRedirections: 0,
9+
});
10+
11+
console.log(response.statusCode);

lib/http-client.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,13 @@ export default class HttpClient {
7676
}
7777

7878
async #request(options = {}) {
79-
const { statusCode, headers, trailers, body } = await request(options);
79+
const { statusCode, headers, trailers, body } = await request({
80+
...options,
81+
dispatcher: new Agent({
82+
keepAliveTimeout: 10,
83+
keepAliveMaxTimeout: 10,
84+
}),
85+
});
8086

8187
if (this.#throwOn400 && statusCode >= 400 && statusCode <= 499) {
8288
// Body must be consumed; https://github.com/nodejs/undici/issues/583#issuecomment-855384858
@@ -151,6 +157,7 @@ export default class HttpClient {
151157
* Error class for the client
152158
*/
153159
export class HttpClientError extends Error {
160+
static ServerDown = 'EOPENBREAKER';
154161
constructor(message, { code, cause, options }) {
155162
super(message);
156163
this.name = 'HttpClientError';

0 commit comments

Comments
 (0)