(response: Response, maxBytes: number, tooLargeMessage: string)
| 4 | *--------------------------------------------------------------------------------------------*/ |
| 5 | |
| 6 | export async function readTextWithByteLimit(response: Response, maxBytes: number, tooLargeMessage: string): Promise<string> { |
| 7 | const declared = Number(response.headers.get('content-length')); |
| 8 | if (Number.isFinite(declared) && declared > maxBytes) { |
| 9 | throw new Error(tooLargeMessage); |
| 10 | } |
| 11 | |
| 12 | if (!response.body) { |
| 13 | const text = await response.text(); |
| 14 | if (new TextEncoder().encode(text).byteLength > maxBytes) { |
| 15 | throw new Error(tooLargeMessage); |
| 16 | } |
| 17 | return text; |
| 18 | } |
| 19 | |
| 20 | const reader = response.body.getReader(); |
| 21 | const decoder = new TextDecoder(); |
| 22 | let bytes = 0; |
| 23 | let text = ''; |
| 24 | |
| 25 | while (true) { |
| 26 | const { done, value } = await reader.read(); |
| 27 | if (done) break; |
| 28 | bytes += value.byteLength; |
| 29 | if (bytes > maxBytes) { |
| 30 | await reader.cancel(); |
| 31 | throw new Error(tooLargeMessage); |
| 32 | } |
| 33 | text += decoder.decode(value, { stream: true }); |
| 34 | } |
| 35 | |
| 36 | return text + decoder.decode(); |
| 37 | } |
no test coverage detected