通常,awsdk函数是异步的,因此了解如何使用Promises和async/await编写异步JavaScript非常重要。
这里有一种方法,它更线性,希望更容易遵循。
const AWS = require('aws-sdk');
const _ = require('lodash');
const S3 = new AWS.S3({
region: 'ap-south-1',
apiVersion: '2006-03-01',
});
const cloudwatch = new AWS.CloudWatch({
region: 'ap-south-1',
apiVersion: '2010-08-01',
});
const metrics = async (bucketName) => {
const params = {
EndTime: 1536128999,
MetricDataQueries: [{
Id: 'm17',
MetricStat: {
Metric: {
Dimensions: [
{
Name: 'BucketName',
Value: bucketName,
},
{
Name: 'StorageType',
Value: 'StandardStorage',
},
],
MetricName: 'BucketSizeBytes',
Namespace: 'AWS/S3',
},
Period: 86400,
Stat: 'Sum',
Unit: 'Bytes',
},
ReturnData: true,
}],
StartTime: 1536085800,
};
return cloudwatch.getMetricData(params).promise();
};
exports.handler = async (event) => {
try {
const bucketData = await S3.listBuckets({}).promise();
const bucketNames = _.map(bucketData.Buckets, bucket => bucket.Name);
const bucketMetrics = await Promise.all(_.map(bucketNames, bucket => metrics(bucket)));
const bucketSizes = bucketMetrics.map(m => m.MetricDataResults[0].Values[0] || 0);
return _.zipWith(bucketNames, bucketSizes, (bn, bs) => ({ bucket: bn, size: bs }));
} catch (err) {
console.log(err.message);
throw err;
}
};
此代码的结果如下所示:
[
{
"bucket": "mybucket-of-images",
"size": 1209721781
},
{
"bucket": "backup-project",
"size": 2048
}
]