diff --git a/lib/http-client.js b/lib/http-client.js index dd90a2f..14cd4d6 100644 --- a/lib/http-client.js +++ b/lib/http-client.js @@ -37,6 +37,7 @@ export default class HttpClient { */ constructor({ abortController = undefined, + agent = undefined, autoRenewAbortController = false, clientName = '', connections = 50, @@ -96,12 +97,14 @@ export default class HttpClient { } } - this.#agent = new Agent({ - keepAliveMaxTimeout, - keepAliveTimeout, - connections, - pipelining, - }); + this.#agent = + agent || + new Agent({ + keepAliveMaxTimeout, + keepAliveTimeout, + connections, + pipelining, + }); if (fallback) { if (typeof fallback === 'string') { @@ -121,6 +124,7 @@ export default class HttpClient { return this.#metrics; } + // TODO add some type support for these options async #request(options = {}) { if (options.redirectable) { const { redirect } = interceptors; @@ -130,6 +134,18 @@ export default class HttpClient { } else { options.dispatcher = this.#agent; } + if (options.retries) { + const { retry } = interceptors; + console.log(options.dispatcher); + options.dispatcher = this.#agent.compose( + retry({ + retry: function () { + console.log('-------------------'); + }, + maxRetries: options.retries, + }), + ); + } const { statusCode, headers, trailers, body } = await request({ ...options, @@ -185,6 +201,7 @@ export default class HttpClient { * @returns {Promise} */ async request(options = {}) { + console.log('............', options); return await this.#breaker.fire(options); } diff --git a/tests/http-client.test.js b/tests/http-client.test.js index ea1a047..7b4a7b2 100644 --- a/tests/http-client.test.js +++ b/tests/http-client.test.js @@ -4,6 +4,7 @@ import http from 'node:http'; import HttpClient from '../lib/http-client.js'; import { wait } from './utilities.js'; +import { MockAgent, setGlobalDispatcher } from 'undici'; let httpServer, host = 'localhost', @@ -205,6 +206,35 @@ await test('http-client - redirects', async (t) => { }); }); +await test('http-client - retries', async (t) => { + await t.test( + `uses the 'retries' options on incoming requests`, + async () => { + const agent = new MockAgent(); + agent.disableNetConnect(); + // setGlobalDispatcher(agent); + agent + .get('http://somepath.dk') + .intercept({ + path: '/', + method: 'GET', + }) + .reply(400, {}); + + const client = new HttpClient({ agent }); + await client.request({ + path: '/', + origin: 'http://somepath.dk', + method: 'GET', + retries: 2, + dispatcher: agent, + }); + strictEqual(agent._eventsCount, 2); + agent.assertNoPendingInterceptors(); + }, + ); +}); + await test('http-client - circuit breaker behaviour', async (t) => { const url = `http://${host}:${port}`; beforeEach(startServer);