我对无服务器框架和AWS lambda完全陌生。
向http://localhost:3000/user/1e89a3f0-d170-11e9-94bd-91e9ae84f3e9发出GET请求时,我希望响应将与匹配密钥的有效JSON对象一起发送回浏览器。就像唯一退出控制台一样。而且不是空文件。
我返回错误吗?我在调试该代码时遇到了困难,如果我的lambda函数或问题出在哪里,我现在就不知道了。
谢谢。
console.log
声明
{
email: 'i@am.com',
password: '$argon2i$v=19$m=4096,t=3,p=1$IIICgcMqbUA7wFpEMqb/GA$ENScjko+Y8pruQsTiE6qN81QAJfAPX/T116RQZqe347Y1p0rez4KhKaEulMeabKKiu8',
id: '1e89a3f0-d170-11e9-94bd-91e9ae84f3e9'
}
这里是有问题的获取处理程序。
users / get.js
const AWS = require("aws-sdk");
const dynamoDb = new AWS.DynamoDB.DocumentClient({
region: "localhost",
endpoint: "http://localhost:8000"
});
module.exports.get = async event => {
const params = {
TableName: process.env.DYNAMODB_TABLE,
Key: {
id: event.pathParameters.id
}
};
dynamoDb.get(params, (error, result) => {
if (error) {
console.error(error);
return;
}
console.log(result.Item); // logs successfully to the console.
return {
// doesn't return a response.
statusCode: 200,
body: JSON.stringify(result.Item)
};
});
};
serverless.yml
# EXCERPT
functions:
get:
handler: users/get.get
events:
- http:
method: get
path: user/{id}
cors: true
resources:
Resources:
UsersDynamoDbTable:
Type: "AWS::DynamoDB::Table"
DeletionPolicy: Retain
Properties:
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: ${self:provider.environment.DYNAMODB_TABLE}
custom:
dynamodb:
stages:
- dev
start:
port: 8000
inMemory: true
sharedDb: true
noStart: true
答案 0 :(得分:0)
您应该使用callback参数返回响应:
module.exports.get = (event, context, callback) => {
const params = {
TableName: process.env.DYNAMODB_TABLE,
Key: {
id: event.pathParameters.id,
},
};
dynamoDb.get(params, (error, result) => {
if (error) {
console.error(error);
callback({
statusCode: 500,
body: 'Unable to get item',
});
}
console.log(result.Item);
callback(null, {
statusCode: 200,
body: JSON.stringify(result.Item),
});
});
};
或使用承诺:
module.exports.get = async event => {
try {
const params = {
TableName: process.env.DYNAMODB_TABLE,
Key: {
id: event.pathParameters.id,
},
};
const result = await dynamoDb.get(params).promise();
console.log(result.Item);
return {
statusCode: 200,
body: JSON.stringify(result.Item),
};
} catch (error) {
console.error(error);
return {
statusCode: 500,
body: 'Unable to get item',
};
}
};