From ea3950967dca7a84442388419eb26a0ac1db8fe6 Mon Sep 17 00:00:00 2001 From: Alex Potsides Date: Wed, 13 Mar 2024 17:54:08 +0100 Subject: [PATCH] fix: stop resolving on signal abort (#2) If the passed signal has been aborted, stop trying to resolve records. --- src/dns.ts | 5 +++++ test/index.spec.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/dns.ts b/src/dns.ts index 6e03e07..c7e1f97 100644 --- a/src/dns.ts +++ b/src/dns.ts @@ -56,6 +56,11 @@ export class DNS implements DNSInterface { const errors: Error[] = [] for (const resolver of resolvers) { + // skip further resolutions if the user aborted the signal + if (options.signal?.aborted === true) { + break + } + try { const result = await resolver(domain, { ...options, diff --git a/test/index.spec.ts b/test/index.spec.ts index 6a66a2c..2f6858b 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -140,4 +140,33 @@ describe('dns', () => { expect(defaultResolver.callCount).to.equal(1) }) + + it('should stop resolving if the user aborts the request', async () => { + const error = new Error('Aborted!') + const controller = new AbortController() + const fake = (): void => { + controller.abort() + + throw error + } + const resolvers = [ + Sinon.stub().callsFake(fake), + Sinon.stub().callsFake(fake), + Sinon.stub().callsFake(fake) + ] + + const resolver = dns({ + resolvers: { + '.': resolvers + } + }) + const result = resolver.query('test-abort-stops-resolving.com', { + signal: controller.signal + }) + + await expect(result).to.eventually.be.rejectedWith(error) + + // only one resolver should have been called + expect(resolvers.reduce((acc, curr) => acc + curr.callCount, 0)).to.equal(1) + }) })