【发布时间】:2016-11-09 08:38:57
【问题描述】:
我是无服务器框架的新手。 学习无服务器最佳实践时。 here
我有一个关于“在您的 Lambda 代码之外初始化外部服务”的问题。 如何实施? 例如:handler.js 中的以下代码
const getOneUser = (event, callback) => {
let response = null;
// validate parameters
if (event.accountid && process.env.SERVERLESS_SURVEYTABLE) {
let docClient = new aws.DynamoDB.DocumentClient();
let params = {
TableName: process.env.SERVERLESS_USERTABLE,
Key: {
accountid: event.accountid,
}
};
docClient.get(params, function(err, data) {
if (err) {
// console.error("Unable to get an item with the request: ", JSON.stringify(params), " along with error: ", JSON.stringify(err));
return callback(getDynamoDBError(err), null);
} else {
if (data.Item) { // got response
// compose response
response = {
accountid: data.Item.accountid,
username: data.Item.username,
email: data.Item.email,
role: data.Item.role,
};
return callback(null, response);
} else {
// console.error("Unable to get an item with the request: ", JSON.stringify(params));
return callback(new Error("404 Not Found: Unable to get an item with the request: " + JSON.stringify(params)), null);
}
}
});
}
// incomplete parameters
else {
return callback(new Error("400 Bad Request: Missing parameters: " + JSON.stringify(event)), null);
}
};
问题是如何在我的 Lambda 代码之外初始化 DynamoDB。
更新 2:
下面的代码优化了吗?
Handler.js
let survey = require('./survey');
module.exports.handler = (event, context, callback) => {
return survey.getOneSurvey({
accountid: event.accountid,
surveyid: event.surveyid
}, callback);
};
survey.js
let docClient = new aws.DynamoDB.DocumentClient();
module.exports = (() => {
const getOneSurvey = (event, callback) {....
docClient.get(params, function(err, data)...
....
};
return{
getOneSurvey : getOneSurvey,
}
})();
【问题讨论】:
-
“下面的代码优化了吗?” 我会说不,不是按照这个规则。每次调用
handler时,都会调用survey.getOneSurvey(),每次发生这种情况时,您都会创建一个新的aws.DynamoDB.DocumentClient。这应该只在最初加载代码时分配给适当范围的变量一次,而不是每次调用处理程序时。 -
好的!我将 docClient 放在 module.exports 之外。它最初会加载并且只创建一个 docClient。我的想法对吗?
标签: node.js amazon-dynamodb serverless-framework