@@ -236,29 +236,37 @@ const saveImageToLocalFs = async (imageBuffer: Buffer): Promise<string> => {
236
236
237
237
const postProcessMessageContent = async ( content : string ) => {
238
238
const contentArray = JSON . parse ( content ) ;
239
- const resultArray = [ ] ;
239
+ const flattenedArray = [ ] ;
240
240
241
241
for ( const c of contentArray ) {
242
242
if ( ! ( 'image' in c ) ) {
243
- resultArray . push ( c ) ;
243
+ flattenedArray . push ( c ) ;
244
244
continue ;
245
245
}
246
246
247
247
// Process image
248
248
const s3Key = c . image . source . s3Key ;
249
249
let imageBuffer : Buffer ;
250
+ let localPath : string ;
250
251
251
252
if ( s3Key in imageCache ) {
252
- imageBuffer = imageCache [ s3Key ] ;
253
+ // Use cached image data and path
254
+ imageBuffer = imageCache [ s3Key ] . data ;
255
+ localPath = imageCache [ s3Key ] . localPath ;
253
256
} else {
254
257
const file = await getBytesFromKey ( s3Key ) ;
255
258
// Convert file to webp
256
259
imageBuffer = await sharp ( file ) . webp ( { lossless : false , quality : 80 } ) . toBuffer ( ) ;
257
- imageCache [ s3Key ] = imageBuffer ;
260
+
261
+ // Save image to local filesystem
262
+ localPath = await saveImageToLocalFs ( imageBuffer ) ;
263
+
264
+ // Cache both the image buffer and local path
265
+ imageCache [ s3Key ] = { data : imageBuffer , localPath } ;
258
266
}
259
267
260
268
// Add image to result
261
- resultArray . push ( {
269
+ flattenedArray . push ( {
262
270
image : {
263
271
format : 'webp' ,
264
272
source : {
@@ -267,14 +275,11 @@ const postProcessMessageContent = async (content: string) => {
267
275
} ,
268
276
} ) ;
269
277
270
- // Save image to local filesystem
271
- const localPath = await saveImageToLocalFs ( imageBuffer ) ;
272
-
273
278
// Add a text block after the image with the path information
274
- resultArray . push ( {
279
+ flattenedArray . push ( {
275
280
text : `the image is stored locally on ${ localPath } ` ,
276
281
} ) ;
277
282
}
278
283
279
- return resultArray ;
284
+ return flattenedArray ;
280
285
} ;
0 commit comments