Skip to content

Commit

Permalink
fix: check signal.aborted (#479)
Browse files Browse the repository at this point in the history
  • Loading branch information
ronag committed Nov 13, 2020
1 parent 85f05ed commit f083cc0
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 8 deletions.
22 changes: 16 additions & 6 deletions lib/abort-signal.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,30 @@ const { RequestAbortedError } = require('./core/errors')
const kListener = Symbol('kListener')
const kSignal = Symbol('kSignal')

function abort (self) {
if (self.abort) {
self.abort()
} else {
self.onError(new RequestAbortedError())
}
}

function addSignal (self, signal) {
self[kSignal] = signal
self[kSignal] = null
self[kListener] = null

if (!signal) {
return
}

if (signal.aborted) {
abort(self)
return
}

self[kSignal] = signal
self[kListener] = () => {
if (self.abort) {
self.abort()
} else {
self.onError(new RequestAbortedError())
}
abort(self)
}

if ('addEventListener' in self[kSignal]) {
Expand Down
4 changes: 2 additions & 2 deletions lib/client-pipeline.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,6 @@ class PipelineHandler extends AsyncResource {
this.handler = handler
this.abort = null

addSignal(this, signal)

this.req = new PipelineRequest().on('error', util.nop)

this.ret = new Duplex({
Expand Down Expand Up @@ -137,6 +135,8 @@ class PipelineHandler extends AsyncResource {
})

this.res = null

addSignal(this, signal)
}

onConnect (abort) {
Expand Down
21 changes: 21 additions & 0 deletions test/abort-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,27 @@ if (global.AbortController) {
})
}
for (const { AbortControllerImpl, controllerName } of controllers) {
test(`Abort ${controllerName} before creating request`, (t) => {
t.plan(1)

const server = createServer((req, res) => {
t.fail()
})
t.teardown(server.close.bind(server))

server.listen(0, () => {
const client = new Client(`http:https://localhost:${server.address().port}`)
const abortController = new AbortControllerImpl()
t.teardown(client.destroy.bind(client))

abortController.abort()

client.request({ path: '/', method: 'GET', signal: abortController.signal }, (err, response) => {
t.ok(err instanceof errors.RequestAbortedError)
})
})
})

test(`Abort ${controllerName} before sending request (no body)`, (t) => {
t.plan(3)

Expand Down

0 comments on commit f083cc0

Please sign in to comment.