Skip to content

Commit a8accfd

Browse files
authored
Abort on error (#19)
* feat: use controller from options if exists. abort fetch if error occurs. * test: check if external abort controller is used
1 parent 21fab07 commit a8accfd

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

src/index.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ class Saturn {
6464
startTime: new Date()
6565
}
6666

67-
const controller = new AbortController()
67+
const controller = options.controller ?? new AbortController()
6868
const connectTimeout = setTimeout(() => {
6969
controller.abort()
7070
}, options.connectTimeout)
@@ -105,7 +105,7 @@ class Saturn {
105105
throw err
106106
}
107107

108-
return { res, log }
108+
return { res, controller, log }
109109
}
110110

111111
/**
@@ -118,7 +118,7 @@ class Saturn {
118118
* @returns {Promise<AsyncIterable<Uint8Array>>}
119119
*/
120120
async * fetchContent (cidPath, opts = {}) {
121-
const { res, log } = await this.fetchCID(cidPath, opts)
121+
const { res, controller, log } = await this.fetchCID(cidPath, opts)
122122

123123
async function * metricsIterable (itr) {
124124
log.numBytesSent = 0
@@ -134,6 +134,8 @@ class Saturn {
134134
yield * extractVerifiedContent(cidPath, itr)
135135
} catch (err) {
136136
log.error = err.message
137+
controller.abort()
138+
137139
throw err
138140
} finally {
139141
this._finalizeLog(log)

test/index.spec.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,19 @@ describe('Saturn client', () => {
5353
await assert.rejects(client.fetchCID(TEST_CID, { connectTimeout: 1 }))
5454
})
5555

56+
it('should use external abort controller', async () => {
57+
const controller = new AbortController()
58+
setTimeout(() => controller.abort(), 5)
59+
60+
await assert.rejects(
61+
client.fetchCID(TEST_CID, { controller }),
62+
{
63+
name: 'AbortError',
64+
message: 'This operation was aborted'
65+
}
66+
)
67+
})
68+
5669
it.skip('should fail when exceeding download timeout', async () => {
5770
await assert.rejects(client.fetchCID(`${TEST_CID}/blah`, { downloadTimeout: 1 }))
5871
})

0 commit comments

Comments
 (0)