I have these two endpoints:
GetImages
media
This is a REST API and I am using AWS Lambda.
The flow here is simple: I hit the getImages
endpoint, it fetches all my images from S3. Goes through them, fetches info about them from a db, build an object out of this and return it to the frontend.
The object looks like this:
const baseUrl = "https://myapp.com";
const modifiedKey = item.Key.replace("uploads/", "");
const dbdData = await getMediaById(modifiedKey);
const imageUrl = `${baseUrl}/api/media/${modifiedKey}`;
return {
url: imageUrl,
width: dbdData.width,
height: dbdData.height,
intrinsicSize: `${dbdData.width}x${dbdData.height}`,
};
Not that the imageUrl
points to the media endpoint.
So far this all works. Now when I want to render it in the frontend I would add something like:
<img src="https://myapp.com/api/media/420a7366-577c-4afa-b85e-b43a8ad540e6?preset=background" />
And this hits the media endpoint, fetches the image from s3 and reads the content type and returns it. Also it resized the image if I send in a width parameter, basically like this:
const s3Params = {
Bucket: process.env.S3_BUCKET_NAME,
Key: `uploads/${imageName}`,
};
try {
const s3Data = await s3.getObject(s3Params).promise();
const imageBuffer = s3Data.Body as Buffer;
const imageData = await resize(
widthParam,
imageBuffer,
imageName,
s3Data
);
}
Return it:
response.writeHead(200, { "Content-Type": imageData.type });
response.write(imageData.buffer, "binary");
response.end(null, "binary");
I also had:
response.type(imageData.type);
response.send(imageData.buffer);
but I don’t see my image, I see:
There are no errors or anything.
I have set my apiGateway
to allow:
apiGateway:
binaryMediaTypes:
- "multipart/form-data"
- "image/*"
- "application/octet-stream"
- "*/*"
My logs show that I am returning buffer with right content type:
INFO RETURNING {
buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 60 00 60 00 00 ff db 00 43 00 03 02 02 03 02 02 03 03 03 03 04 03 03 04 05 08 05 05 04 04 05 0a 07 07 06 ... 85223 more bytes>,
type: 'image/jpeg'
}
I don’t know where I am going wrong here.
3