@@ -11,38 +11,44 @@ const app = new Hono<Env>()
1111 const user = c . var . user ! ;
1212 const fileId = c . req . param ( "id" ) ;
1313
14- const etag = btoa ( `"${ user . id } -${ fileId } "` ) ;
15- c . header ( "ETag" , etag ) ;
16- if ( c . req . header ( "If-None-Match" ) === etag ) {
17- return new Response ( null , {
18- status : 304 ,
19- statusText : "Not Modified" ,
20- } ) ;
21- }
22-
2314 const metadata = await getFileMetadata ( fileId , user . id ) ;
2415 if ( ! metadata ) {
2516 return c . json ( { error : "File not found" } , 404 ) ;
2617 }
2718
19+ // Determine content type based on protocol
20+ let contentType = "image/png" ;
21+ if ( metadata . protocol === "data:" ) {
22+ const base64Header = metadata . accessUrl . split ( "," ) [ 0 ] ;
23+ contentType = base64Header ?. split ( ";" ) [ 0 ] ?. split ( ":" ) [ 1 ] || "image/png" ;
24+ } else if ( metadata . protocol === "file:" ) {
25+ const suffix = metadata . accessUrl . split ( "." ) . pop ( ) ;
26+ contentType = `image/${ suffix } ` ;
27+ }
28+
29+ // Set ETag and check cache
30+ const etag = btoa ( `"${ user . id } -${ fileId } "` ) ;
31+ c . header ( "ETag" , etag ) ;
32+ c . header ( "Content-Type" , contentType ) ;
33+ c . header ( "Cache-Control" , "private, max-age=31536000" ) ;
34+
35+ if ( c . req . header ( "If-None-Match" ) === etag ) {
36+ return c . body ( null , 304 ) ;
37+ }
38+
2839 switch ( metadata . protocol ) {
2940 case "data:" : {
3041 const [ base64Header , base64Data ] = metadata . accessUrl . split ( "," ) ;
3142 if ( ! base64Header || ! base64Data ) {
3243 return c . json ( { error : "Invalid file data" } , 500 ) ;
3344 }
34- // Set the content type based on the header
35- const contentType = base64Header . split ( ";" ) [ 0 ] ?. split ( ":" ) [ 1 ] || "image/png" ;
36- c . header ( "Content-Type" , contentType ) ;
3745 return stream ( c , async ( stream ) => {
3846 const buffer = Buffer . from ( base64Data , "base64" ) ;
3947 await stream . write ( buffer ) ;
4048 } ) ;
4149 }
4250 case "file:" : {
43- const suffix = metadata . accessUrl . split ( "." ) . pop ( ) ;
4451 const fileBuffer = await fs . readFile ( metadata . accessUrl ) ;
45- c . header ( "Content-Type" , `image/${ suffix } ` ) ;
4652 return stream ( c , async ( stream ) => {
4753 await stream . write ( fileBuffer ) ;
4854 } ) ;
0 commit comments