@@ -3,6 +3,11 @@ import { makeAPIErrorResponse, makeUnauthenticatedAPIErrorResponse } from "@/com
33import { session } from "@/composition"
44import { env } from "@/common"
55
6+ const ErrorName = {
7+ MAX_FILE_SIZE_EXCEEDED : "MaxFileSizeExceededError" ,
8+ TIMEOUT : "TimeoutError"
9+ }
10+
611export 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