Javascript 调用DynamoDB查询,然后将结果写入s3 bucket:如何使用async wait简化此代码?
我有下面的lambda函数,它从DynamoDB表读取数据,然后将结果写入S3存储桶上的电子表格 它工作得很好,但我想使用async await来改进它。这可能吗Javascript 调用DynamoDB查询,然后将结果写入s3 bucket:如何使用async wait简化此代码?,javascript,node.js,amazon-dynamodb,Javascript,Node.js,Amazon Dynamodb,我有下面的lambda函数,它从DynamoDB表读取数据,然后将结果写入S3存储桶上的电子表格 它工作得很好,但我想使用async await来改进它。这可能吗 'use strict'; const AWS = require('aws-sdk'); const S3 = new AWS.S3(); const excel = require('excel4node'); const workbook = new excel.Workbook(); const worksheet = wor
'use strict';
const AWS = require('aws-sdk');
const S3 = new AWS.S3();
const excel = require('excel4node');
const workbook = new excel.Workbook();
const worksheet = workbook.addWorksheet('Sheet 1');
const db = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10'});
const contactsTable = process.env.CONTACTS_TABLE;
const contactsBucket = process.env.CONTACTS_BUCKET;
const bucketRegion = process.env.REGION;
module.exports.exportContactsByID = (event, _context, callback) => {
const id = event.pathParameters.id;
const params = {
TableName: contactsTable,
IndexName: "company_id-created_at-index",
KeyConditionExpression: "company_id = :v_ID",
ExpressionAttributeValues: {
":v_ID": id,
},
ProjectionExpression: "company_name, contact_name, age, phone, email, dsr_ratio, max_eligibility, created_at_local, selected_banks"
};
return db.query(params).promise()
.then((res) => {
const items = res.Items;
if(res.Count === 0){
return callback(null, response(200, `No records found for id ${id}`));
}
// Headers + Columns
worksheet.cell(1, 1).string('Client').style({font: {bold: true}});
worksheet.cell(1, 2).string('Name').style({font: {bold: true}});
worksheet.cell(1, 3).string('Age').style({font: {bold: true}});
worksheet.cell(1, 4).string('Email').style({font: {bold: true}});
worksheet.cell(1, 5).string('Phone').style({font: {bold: true}});
worksheet.cell(1, 6).string('DSR Ratio').style({font: {bold: true}});
worksheet.cell(1, 7).string('Max Eligibility').style({font: {bold: true}});
worksheet.cell(1, 8).string('Submission Date').style({font: {bold: true}});
worksheet.cell(1, 9).string('Banks').style({font: {bold: true}});
// Rows
items.forEach((item, i) => {
worksheet.cell(i + 2, 1).string(item.company_name);
worksheet.cell(i + 2, 2).string(item.contact_name);
worksheet.cell(i + 2, 3).string(item.age);
worksheet.cell(i + 2, 4).string(item.email);
worksheet.cell(i + 2, 5).string(item.phone);
worksheet.cell(i + 2, 6).string(item.dsr_ratio);
worksheet.cell(i + 2, 7).string(item.max_eligibility);
worksheet.cell(i + 2, 8).string(item.created_at_local);
worksheet.cell(i + 2, 9).string(item.selected_banks);
});
return workbook.writeToBuffer().then(buffer => {
const params = {
Bucket: contactsBucket,
Key: `contacts/${id}.xlsx`,
Body: buffer,
ACL: 'public-read'
}
const fileURL = `https://${contactsBucket}.s3-${bucketRegion}.amazonaws.com/contacts/${id}.xlsx`;
return S3.upload(params).promise().then(_data => {
callback(null, response(200, fileURL));
});
})
})
.catch((err) => callback(null, response(err.statusCode, err)));
};
上面的代码是我的原始代码的改进版本。感谢您的阅读。阅读后,我将代码简化为以下内容-通过让多个等待
module.exports.exportContactsByID = async (event, _context) => {
const id = event.pathParameters.id;
const params = {
TableName: contactsTable,
IndexName: "company_id-created_at-index",
KeyConditionExpression: "company_id = :v_ID",
ExpressionAttributeValues: {
":v_ID": id,
},
ProjectionExpression: "company_name, contact_name, age, phone, email, dsr_ratio, max_eligibility, created_at_local, selected_banks"
};
try {
const res = await db.query(params).promise();
if(res.Count === 0){
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
status: `No records found for company id ${id}`,
}),
};
return response;
}
else {
// Headers + Columns
const items = res.Items;
worksheet.cell(1, 1).string('Client').style({font: {bold: true}});
worksheet.cell(1, 2).string('Name').style({font: {bold: true}});
worksheet.cell(1, 3).string('Age').style({font: {bold: true}});
worksheet.cell(1, 4).string('Email').style({font: {bold: true}});
worksheet.cell(1, 5).string('Phone').style({font: {bold: true}});
worksheet.cell(1, 6).string('DSR Ratio').style({font: {bold: true}});
worksheet.cell(1, 7).string('Max Eligibility').style({font: {bold: true}});
worksheet.cell(1, 8).string('Submission Date').style({font: {bold: true}});
worksheet.cell(1, 9).string('Banks').style({font: {bold: true}});
// Rows
items.forEach((item, i) => {
worksheet.cell(i + 2, 1).string(item.company_name);
worksheet.cell(i + 2, 2).string(item.contact_name);
worksheet.cell(i + 2, 3).string(item.age);
worksheet.cell(i + 2, 4).string(item.email);
worksheet.cell(i + 2, 5).string(item.phone);
worksheet.cell(i + 2, 6).string(item.dsr_ratio);
worksheet.cell(i + 2, 7).string(item.max_eligibility);
worksheet.cell(i + 2, 8).string(item.created_at_local);
worksheet.cell(i + 2, 9).string(item.selected_banks);
});
const buffer = await workbook.writeToBuffer();
const params = {
Bucket: contactsBucket,
Key: `contacts/${id}.xlsx`,
Body: buffer,
ACL: 'public-read'
}
const fileURL = `https://${contactsBucket}.s3-${bucketRegion}.amazonaws.com/contacts/${id}.xlsx`;
const s3 = await S3.upload(params).promise();
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
fileURL: fileURL,
}),
};
return response;
}
}
catch (err){
console.log(err);
return err;
}
};
工作表
和工作簿
来自哪里?此外,工作表似乎没有在任何地方使用。糟糕,我已经更新了代码。我正在使用excel4node包来写入S3电子表格。它看起来非常好。但是,我会删除外部try
…catch
,以便调用者(Lambda引擎)处理错误。或者,至少,重新显示异常而不是返回异常。感谢您的友好反馈。如果我删除try…catch语句,调用方将如何处理错误?我能看到一些例子吗?为noob的问题道歉,我仍然在Lambda周围寻找我的方法。按照目前的写作方式,你正在接受例外。随它们去吧,这样异常将拒绝异步函数调用返回的承诺。Lambda运行时将捕获它并进行相应的处理。您可以自己尝试:module.exports.raiseException=async()=>{throw new Error('magic?')}
。