我想要的只是
被调用时,端点将从https://dog.ceo/api/breeds/image/random检索狗的品种图片
图像应存储在AWS S3存储桶中。 与图像有关的以下信息应存储在数据库中:
狗的品种名称;
图片的上传日期;
上传的图片的S3位置。
发布请求代码
module.exports.createPost = (event, context, callback) => {
let url = 'https://dog.ceo/api/breeds/image/random';
let options = {json: true};
var s3 = new AWS.S3();
request(url, options, (error, res, body) => {
if (error) {
return console.log(error);
}
const breed = body.message.split('/');
if (!error && res.statusCode == 200) {
const post = {
id: uuid(),
name: breed[4],
createdAt: new Date().toISOString(),
message: body.message,
status: body.status,
};
/*****************Code to Upload an Image Starts here*************************** */
function put_from_url(url, bucket, key, callback) {
request(
{
url: url,
encoding: null,
},
function(err, res, body) {
if (err) return callback(err, res);
s3.putObject(
{
Bucket: bucket,
Key: key,
ContentType: res.headers['content-type'],
ContentLength: res.headers['content-length'],
Body: body, // buffer
},
callback,
);
},
);
}
put_from_url(`${body.message}`, 'backendpics', `${breed[4]}.jpg`, function(err, res) {
if (err) throw err;
console.log('Uploaded data successfully!');
});
/*****************Code to Upload an Image Ends here*************************** */
return db
.put({
TableName: postsTable,
Item: post,
})
.promise()
.then(() => {
callback(null, response(201, post));
})
.catch((err) => response(null, response(err.statusCode, err)));
}
});
};
代码,用于从发布请求中将图像数据上传到数据库
module.exports.createPost = (event, context, callback) => {
let url = 'https://dog.ceo/api/breeds/image/random';
let options = {json: true};
var s3 = new AWS.S3();
request(url, options, (error, res, body) => {
if (error) {
return console.log(error);
}
const breed = body.message.split('/');
if (!error && res.statusCode == 200) {
const post = {
id: uuid(),
name: breed[4],
createdAt: new Date().toISOString(),
message: body.message,
status: body.status,
};
return db
.put({
TableName: postsTable,
Item: post,
})
.promise()
.then(() => {
callback(null, response(201, post));
})
.catch((err) => response(null, response(err.statusCode, err)));
}
});
};
代码以将图像上传到s3存储桶
//Upload an Image
function put_from_url(url, bucket, key, callback) {
request(
{
url: url,
encoding: null,
},
function(err, res, body) {
if (err) return callback(err, res);
s3.putObject(
{
Bucket: bucket,
Key: key,
ContentType: res.headers['content-type'],
ContentLength: res.headers['content-length'],
Body: body, // buffer
},
callback,
);
},
);
}
put_from_url(`${body.message}`, 'backendpics', `${breed[4]}.jpg`, function(err, res) {
if (err) throw err;
console.log('Uploaded data successfully!');
});
如果我分别运行两个代码,两者都可以正常工作,但是如果我在一个发布请求中一起运行它们(第一个代码示例),则仅与图像相关的数据存储在数据库中,但是图像不会存储在s3存储桶中。
有什么办法可以做到异步并等待??