Skip to content

Commit d6dbfb3

Browse files
committed
Fixes blob not returned correctly
1 parent 8845001 commit d6dbfb3

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

src/app/api/proxy/route.ts

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@ import { makeAPIErrorResponse, makeUnauthenticatedAPIErrorResponse } from "@/com
33
import { session } from "@/composition"
44
import { env } from "@/common"
55

6+
const ErrorName = {
7+
MAX_FILE_SIZE_EXCEEDED: "MaxFileSizeExceededError",
8+
TIMEOUT: "TimeoutError"
9+
}
10+
611
export async function GET(req: NextRequest) {
712
const isAuthenticated = await session.getIsAuthenticated()
813
if (!isAuthenticated) {
@@ -25,12 +30,13 @@ export async function GET(req: NextRequest) {
2530
const file = await downloadFile({ url, maxBytes, timeoutInSeconds })
2631
return new NextResponse(file, { status: 200 })
2732
} catch (error) {
33+
console.log(error)
2834
if (error instanceof Error == false) {
2935
return makeAPIErrorResponse(500, "An unknown error occurred.")
3036
}
31-
if (error.name === "AbortError") {
37+
if (error.name === ErrorName.MAX_FILE_SIZE_EXCEEDED) {
3238
return makeAPIErrorResponse(413, "The operation was aborted.")
33-
} else if (error.name === "TimeoutError") {
39+
} else if (error.name === ErrorName.TIMEOUT) {
3440
return makeAPIErrorResponse(408, "The operation timed out.")
3541
} else {
3642
return makeAPIErrorResponse(500, error.message)
@@ -53,7 +59,9 @@ async function downloadFile(params: {
5359
throw new Error("Response body unavailable")
5460
}
5561
let totalBytes = 0
62+
let didExceedMaxBytes = false
5663
const reader = response.body.getReader()
64+
let chunks: Uint8Array[] = []
5765
// eslint-disable-next-line no-constant-condition
5866
while (true) {
5967
// eslint-disable-next-line no-await-in-loop
@@ -62,10 +70,17 @@ async function downloadFile(params: {
6270
break
6371
}
6472
totalBytes += value.length
73+
chunks.push(value)
6574
if (totalBytes >= maxBytes) {
75+
didExceedMaxBytes = true
6676
abortController.abort()
6777
break
6878
}
6979
}
70-
return await response.blob()
80+
if (didExceedMaxBytes) {
81+
const error = new Error("Maximum file size exceeded")
82+
error.name = ErrorName.MAX_FILE_SIZE_EXCEEDED
83+
throw error
84+
}
85+
return new Blob(chunks)
7186
}

0 commit comments

Comments
 (0)