Skip to content

Commit 4f6a37a

Browse files
authored
Fix createUploadRequest swallowing errors (#304)
1 parent 91d3638 commit 4f6a37a

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

src/index.ts

+24-6
Original file line numberDiff line numberDiff line change
@@ -164,35 +164,53 @@ async function createUploadRequest(
164164
]),
165165
finalBoundary
166166
]
167-
const req = getHttpModule(baseUrl).request(`${baseUrl}${urlPath}`, {
167+
const url = new URL(urlPath, baseUrl)
168+
const req: ClientRequest = getHttpModule(baseUrl).request(url, {
168169
method: 'POST',
169170
...options,
170171
headers: {
171172
...options?.headers,
172173
'Content-Type': `multipart/form-data; boundary=${boundary}`
173-
}
174+
},
175+
signal: options.signal
176+
})
177+
let aborted = false
178+
req.on('error', _err => {
179+
aborted = true
180+
})
181+
req.on('close', () => {
182+
aborted = true
174183
})
175184
try {
176185
// Send the request body (headers + files).
177186
for (const part of requestBody) {
187+
if (aborted) {
188+
break
189+
}
178190
if (typeof part === 'string') {
179191
req.write(part)
180192
} else if (typeof part?.pipe === 'function') {
181193
part.pipe(req, { end: false })
182194
// Wait for file streaming to complete.
183195
// eslint-disable-next-line no-await-in-loop
184196
await events.once(part, 'end')
185-
// Ensure a new line after file content.
186-
req.write('\r\n')
197+
if (!aborted) {
198+
// Ensure a new line after file content.
199+
req.write('\r\n')
200+
}
187201
} else {
188202
throw new TypeError(
189203
'Socket API - Invalid multipart part, expected string or stream'
190204
)
191205
}
192206
}
207+
} catch (err) {
208+
req.destroy(err as Error)
209+
throw err
193210
} finally {
194-
// Close request after writing all data.
195-
req.end()
211+
if (!aborted) {
212+
req.end()
213+
}
196214
}
197215
return await getResponse(req)
198216
}

0 commit comments

Comments
 (0)