11import axios from 'axios'
22import sharp from 'sharp'
3- import { getPayloadOpts } from './common/methods'
3+ import { acceptCorsHeaders , getPayloadOpts , log } from './common/methods'
44
55export default async ( req : Request ) => {
6+ log ( '[resize] Incoming request' , { method : req . method , url : req . url } )
7+
68 const { url, width, format = 'webp' , rotate } = await getPayloadOpts ( req )
7- const headers : any = {
8- 'Cache-Control' : 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0' ,
9- 'Access-Control-Allow-Origin' : '*' ,
10- 'Access-Control-Allow-Methods' : 'GET, POST, OPTIONS' ,
11- 'Access-Control-Allow-Headers' : '*' ,
12- }
13- let body ,
14- status = 200
9+ log ( '[resize] Parsed query params' , { url, width, format, rotate } )
10+
11+ const headers = acceptCorsHeaders ( )
12+ headers [ 'Cache-Control' ] = 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'
13+
14+ let body
15+ let status = 200
1516
1617 if ( ! url ) {
1718 status = 400
1819 body = 'Missing required query params: url'
20+ log ( '[resize] Missing url parameter' , { } , 'error' )
1921 }
2022
2123 let widthNum
@@ -24,29 +26,35 @@ export default async (req: Request) => {
2426 if ( isNaN ( widthNum ) || widthNum <= 0 ) {
2527 status = 400
2628 body = 'Invalid width parameter'
29+ log ( '[resize] Invalid width parameter' , { width } , 'error' )
2730 }
2831 }
2932
3033 if ( ! body ) {
3134 try {
32- // Fetch source image
35+ log ( '[resize] Fetching source image' , { url } )
3336 const response = await axios . get ( url , { responseType : 'arraybuffer' } )
3437 const inputBuffer = Buffer . from ( response . data )
38+ log ( '[resize] Image fetched, size' , { bytes : inputBuffer . length } )
3539
36- // Resize and convert
37- let outputBuffer = sharp ( inputBuffer ) . rotate ( rotate )
40+ const rotation = rotate ? parseInt ( rotate , 10 ) : undefined
41+ // Create Sharp instance
42+ let transformer = sharp ( inputBuffer ) . rotate ( rotation )
43+ log ( '[resize] Applied rotation' , { rotation } )
3844
3945 if ( widthNum ) {
40- outputBuffer = outputBuffer . resize ( { width : widthNum } )
46+ transformer = transformer . resize ( { width : widthNum } )
47+ log ( '[resize] Applied resizing' , { width : widthNum } )
4148 }
4249
43- const output = await outputBuffer . toFormat ( format as keyof sharp . FormatEnum ) . toBuffer ( )
50+ const output = await transformer . toFormat ( format as keyof sharp . FormatEnum ) . toBuffer ( )
51+ log ( '[resize] Image transformed' , { format, finalSize : output . length } )
4452
4553 status = 200
4654 headers [ 'Content-Type' ] = `image/${ format } `
4755 body = output
4856 } catch ( err : any ) {
49- console . error ( ' Error resizing image: ', err )
57+ log ( '[resize] Error during image processing ', { message : err . message } , 'error' )
5058 status = 500
5159 body = 'Failed to resize image'
5260 }
0 commit comments