Skip to content

Commit 39ce5a8

Browse files
jluterekdaern91
andauthored
fix(sdk-middleware-http): abortController timing (#1600)
Co-authored-by: Daniel Eriksson <[email protected]>
1 parent da0bd42 commit 39ce5a8

File tree

2 files changed

+39
-6
lines changed

2 files changed

+39
-6
lines changed

packages/sdk-middleware-http/src/http.js

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -90,12 +90,6 @@ export default function createHttpMiddleware({
9090
// eslint-disable-next-line
9191
abortController = _abortController || new AbortController()
9292

93-
let timer
94-
if (timeout)
95-
timer = setTimeout(() => {
96-
abortController.abort()
97-
}, timeout)
98-
9993
return (next: Next): Next => (
10094
request: MiddlewareRequest,
10195
response: MiddlewareResponse
@@ -125,6 +119,12 @@ export default function createHttpMiddleware({
125119
let retryCount = 0
126120
// wrap in a fn so we can retry if error occur
127121
function executeFetch() {
122+
// Kick off timer for abortController directly before fetch.
123+
let timer
124+
if (timeout)
125+
timer = setTimeout(() => {
126+
abortController.abort()
127+
}, timeout)
128128
// $FlowFixMe
129129
fetcher(url, fetchOptions)
130130
.then(

packages/sdk-middleware-http/test/http.spec.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,39 @@ describe('Http', () => {
134134
httpMiddleware(next)(request, response)
135135
}))
136136

137+
test('execute a request with timeout and client re-use', () =>
138+
new Promise((resolve, reject) => {
139+
const request = createTestRequest({
140+
uri: '/foo/bar',
141+
})
142+
const response = { resolve, reject }
143+
const next = (req, res) => {
144+
expect(res).toEqual({
145+
...response,
146+
body: { foo: 'bar' },
147+
statusCode: 200,
148+
})
149+
resolve()
150+
}
151+
// Use default options
152+
const httpMiddleware = createHttpMiddleware({
153+
host: testHost,
154+
timeout: 100, // time out after 100ms
155+
fetch,
156+
abortController: new AbortController(),
157+
})
158+
nock(testHost)
159+
.defaultReplyHeaders({
160+
'Content-Type': 'application/json',
161+
})
162+
.get('/foo/bar')
163+
.reply(200, { foo: 'bar' })
164+
// Set delay to emulate instantiated SDK sitting idle
165+
setTimeout(() => {
166+
httpMiddleware(next)(request, response)
167+
}, 110)
168+
}))
169+
137170
test('should accept HEAD request and return without response body', () =>
138171
new Promise((resolve, reject) => {
139172
const request = createTestRequest({ uri: '/foo', method: 'HEAD' })

0 commit comments

Comments
 (0)