【发布时间】:2023-01-24 23:05:06
【问题描述】:
我有一组从 SQS 消息中获取的图像 url。我需要下载图像并将它们存储在 S3 存储桶中。如果下载或存储图像失败,我需要捕获错误,以便将图像推送到另一个 SQS 队列以便稍后重试。
到目前为止,我确实下载并存储了图像,但我不知道如何访问 fetch 和 putObject 函数的结果。此外,我不确定我是否以正确的方式进行此操作,或者是否有更有效/更好/优雅的方式来执行此操作。
这就是我现在所拥有的
const AWS = require("aws-sdk");
const fetch = require("node-fetch")
const s3 = new AWS.S3();
exports.handler = function(event, context) {
// SQS may invoke with multiple messages
for (const message of event.Records) {
const bodyData = JSON.parse(message.body);
const bucket = 'my_images_bucket';
const images = bodyData.images;
let urls = [];
for (const image of images) {
urls.push(image);
}
let promises = urls.map(image => {
fetch(image)
.then((response) => {
if (!response.ok) {
throw new Error('An error occurred while fetching ' + image + ': ' + response.statusText);
}
return response;
})
.then(async res => {
try {
const buffer = await res.buffer();
console.log(image);
// store
return s3.putObject(
{
Bucket: bucket,
Key: image,
Body: buffer,
ContentType: "image/jpeg"
}
).promise();
} catch (e) {
console.log('An error occurred while storing image ' + image + ': ' + e);
}
})
.catch((error) => {
console.error(error);
});
});
Promise.all(promises)
.then(d => {
console.log('All images downloaded.');
console.log('PromiseAll result: ' + d);
}).catch(e => {
console.log('Whoops something went wrong!', e);
});
}
}
我从中得到的输出:
INFO All images downloaded.
INFO PromiseAll result: ,,,,
INFO https://myserver/10658272812/image14.jpg
INFO https://myserver/10658272810/image12.jpg
INFO https://myserver/10658272804/image6.jpg
INFO https://myserver/10658272813/image15.jpg
INFO https://myserver/10658272816/image18.jpg
【问题讨论】:
标签: node.js amazon-s3 aws-lambda promise