Skip to content

Commit

Permalink
Abort on error (#19)
Browse files Browse the repository at this point in the history
* feat: use controller from options if exists. abort fetch if error occurs.

* test: check if external abort controller is used
  • Loading branch information
guanzo authored Oct 12, 2023
1 parent 21fab07 commit a8accfd
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class Saturn {
startTime: new Date()
}

const controller = new AbortController()
const controller = options.controller ?? new AbortController()
const connectTimeout = setTimeout(() => {
controller.abort()
}, options.connectTimeout)
Expand Down Expand Up @@ -105,7 +105,7 @@ class Saturn {
throw err
}

return { res, log }
return { res, controller, log }
}

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

async function * metricsIterable (itr) {
log.numBytesSent = 0
Expand All @@ -134,6 +134,8 @@ class Saturn {
yield * extractVerifiedContent(cidPath, itr)
} catch (err) {
log.error = err.message
controller.abort()

throw err
} finally {
this._finalizeLog(log)
Expand Down
13 changes: 13 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,19 @@ describe('Saturn client', () => {
await assert.rejects(client.fetchCID(TEST_CID, { connectTimeout: 1 }))
})

it('should use external abort controller', async () => {
const controller = new AbortController()
setTimeout(() => controller.abort(), 5)

await assert.rejects(
client.fetchCID(TEST_CID, { controller }),
{
name: 'AbortError',
message: 'This operation was aborted'
}
)
})

it.skip('should fail when exceeding download timeout', async () => {
await assert.rejects(client.fetchCID(`${TEST_CID}/blah`, { downloadTimeout: 1 }))
})
Expand Down

0 comments on commit a8accfd

Please sign in to comment.