【发布时间】:2023-04-06 11:11:01
【问题描述】:
我有一个带有基本端点的示例 SAM 应用程序。我只想通过以下方式在本地运行它:
sam local invoke -e events/event-post-item.json putItemFunction --profile myprofile -n local.json
local.json如下:
{
"getAllItems": {
"SAMPLE_TABLE": "mywebservices-SampleTable-1BS18COYN2SHV"
},
"getById": {
"SAMPLE_TABLE": "mywebservices-SampleTable-1BS18COYN2SHV"
},
"putItem": {
"SAMPLE_TABLE": "mywebservices-SampleTable-1BS18COYN2SHV"
}
}
下面是putItemFunction的代码
// Create clients and set shared const values outside of the handler
// Create a DocumentClient that represents the query to add an item
const dynamodb = require('aws-sdk/clients/dynamodb');
const docClient = new dynamodb.DocumentClient();
// Get the DynamoDB table name from environment variables
const tableName = process.env.SAMPLE_TABLE;
/**
* A simple example includes a HTTP post method to add one item to a DynamoDB table.
*/
exports.putItemHandler = async (event) => {
const { body, httpMethod, path } = event;
if (httpMethod !== 'POST') {
throw new Error(`postMethod only accepts POST method, you tried: ${httpMethod} method.`);
}
// All log statements are written to CloudWatch by default. For more information, see
// https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-logging.html
console.log('received:', JSON.stringify(event));
// Get id and name from the body of the request
const { id, name } = JSON.parse(body);
// Creates a new item, or replaces an old item with a new item
// https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property
const params = {
TableName: tableName,
Item: { id, name },
};
await docClient.put(params).promise();
const response = {
statusCode: 200,
body,
};
console.log(`response from: ${path} statusCode: ${response.statusCode} body: ${response.body}`);
return response;
};
我运行此程序,但出现“找不到资源”错误。我已确保个人资料详细信息正确无误。
问题在于处理程序中的这一行:const tableName = process.env.SAMPLE_TABLE;
如果我在这里硬编码表名,它可以正常工作。否则该函数总是产生tableName 值“SampleTable”...
它应该采用我提供的环境变量的值。不是“SampleTable”...我做错了什么?
【问题讨论】:
标签: amazon-web-services aws-lambda amazon-dynamodb