Skip to content

Commit 34d8a95

Browse files
fix(types): improve type safety in create-stream-promise util (#7855)
This commit improves the type safety of the `create-stream-promise` utility by: - Correctly typing the `data` variable as `Buffer[]` to ensure type-safe usage with `Buffer.concat`. - Typing the `timeoutId` as `NodeJS.Timeout | null` to remove ambiguity. - Explicitly typing the `chunk` parameter as `Buffer`. - Generalizing the `stream` parameter to `Readable` for wider use. - Removing now-obsolete `@ts-expect-error` comments. Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com> Co-authored-by: Philippe Serhal <philippe.serhal@netlify.com>
1 parent 665fa01 commit 34d8a95

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

src/utils/create-stream-promise.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,29 @@
11
import { Buffer } from 'buffer'
2-
import { IncomingMessage } from 'http'
2+
import type { Readable } from 'stream'
33

44
const SEC_TO_MILLISEC = 1e3
55

66
// 6 MiB
77
const DEFAULT_BYTES_LIMIT = 6e6
88

99
const createStreamPromise = function (
10-
stream: IncomingMessage,
10+
stream: Readable,
1111
timeoutSeconds: number,
1212
bytesLimit = DEFAULT_BYTES_LIMIT,
1313
): Promise<Buffer> {
1414
return new Promise(function streamPromiseFunc(resolve, reject) {
15-
let data: unknown[] | null = []
15+
let data: Buffer[] | null = []
1616
let dataLength = 0
1717

18-
// @ts-expect-error TS(7034) FIXME: Variable 'timeoutId' implicitly has type 'any' in ... Remove this comment to see the full error message
19-
let timeoutId: NodeJS.Timeout = null
18+
let timeoutId: NodeJS.Timeout | null = null
2019
if (timeoutSeconds != null && Number.isFinite(timeoutSeconds)) {
2120
timeoutId = setTimeout(() => {
2221
data = null
2322
reject(new Error('Request timed out waiting for body'))
2423
}, timeoutSeconds * SEC_TO_MILLISEC)
2524
}
2625

27-
stream.on('data', function onData(chunk) {
26+
stream.on('data', function onData(chunk: Buffer) {
2827
if (!Array.isArray(data)) {
2928
// Stream harvesting closed
3029
return
@@ -41,12 +40,15 @@ const createStreamPromise = function (
4140
stream.on('error', function onError(error) {
4241
data = null
4342
reject(error)
44-
clearTimeout(timeoutId)
43+
if (timeoutId) {
44+
clearTimeout(timeoutId)
45+
}
4546
})
4647
stream.on('end', function onEnd() {
47-
clearTimeout(timeoutId)
48+
if (timeoutId) {
49+
clearTimeout(timeoutId)
50+
}
4851
if (data) {
49-
// @ts-expect-error TS(7005) FIXME: Variable 'data' implicitly has an 'any[]' type.
5052
resolve(Buffer.concat(data))
5153
}
5254
})

0 commit comments

Comments
 (0)