【发布时间】:2023-03-23 22:58:01
【问题描述】:
我有一个几天前写的 lambda 函数,它在测试时表现得非常好。今天去测试后(不更改任何代码),我收到以下错误:"Invalid lambda function output : Invalid JSON"。
这里是函数代码(Node.js 10.x):
const AWS = require("aws-sdk");
const joi = require("@hapi/joi");
const Cognito = new AWS.CognitoIdentityServiceProvider();
exports.handler = async (event) => {
// NOTE: Cognito expects Username to be the user's email
// Vars
const userPoolId = process.env.COGNITO_USER_POOL_ID;
const {email : UNSAFE_EMAIL, language : UNSAFE_LANGUAGE = "en-US"} = event;
// Normalize email and language
const UNSAFE_TRIMMED_EMAIL = UNSAFE_EMAIL.trim();
const UNSAFE_TRIMMED_LANGUAGE = UNSAFE_LANGUAGE.trim();
// Validate UNSAFE_INPUTS
const languageRegex = /^[a-z]{2}-[A-Z]{2}$/;
const schema = joi.object().keys({
email: joi.string().trim().email({minDomainSegments: 2}).required(),
language: joi.string().trim().min(2).max(5).regex(languageRegex).required()
});
const validationResult = joi.validate({
email: UNSAFE_TRIMMED_EMAIL,
language: UNSAFE_TRIMMED_LANGUAGE
}, schema);
if(validationResult.error) {
console.log(JSON.stringify(validationResult.error, null, 2));
return {
statusCode: 400,
body: JSON.stringify({
error: true,
error_message: "Invalid"
})
}
}
// Validation successful, change variable names to reflect
const VALIDATED_EMAIL = UNSAFE_TRIMMED_EMAIL;
const VALIDATED_LANGUAGE = UNSAFE_TRIMMED_LANGUAGE;
// Cognito params
// Username is the user's email
// email is also required in UserAttributes in order to send confirmation
// DesiredDeliveryMediums is required to send confirmation
const params = {
UserPoolId: userPoolId,
Username: VALIDATED_EMAIL,
UserAttributes: [
{
Name: "email",
Value: VALIDATED_EMAIL
},
{
Name: "custom:language",
Value: VALIDATED_LANGUAGE
}
],
DesiredDeliveryMediums: ["EMAIL"]
}
// Attempt to create user in Cognito
try {
const authRes = await Cognito.adminCreateUser(params).promise();
console.log("Success: ", JSON.stringify(authRes, null, 2));
return {
statusCode: 200,
body: JSON.stringify({
success: true
})
}
} catch(err) {
console.log("Error: ", JSON.stringify(err, null, 2));
return {
statusCode: 400,
body: JSON.stringify({
error: true,
error_message: err.message
})
}
}
};
运行测试时,我在传入格式错误的事件数据时收到了预期的错误消息,并且在尝试两次使用相同的电子邮件创建用户时收到了 Cognito 错误。同样,这是意料之中的。但是,当传入用户池中没有用户的有效电子邮件时,我得到以下回复(为便于阅读而格式化):
Response:
{
"statusCode": 400,
"body": {
"error": true,
"error_message": "Invalid lambda function output : Invalid JSON"
}
}
查看此函数连接到的 Cognito 用户池,我看到一个用户已成功创建。然而,没有像几天前那样向该电子邮件地址发送电子邮件。
所有记录的信息都表明我有一个无效的 JSON 错误,根本没有 authRes 记录。当删除对 Cognito 的调用和相应的 console.log 调用时,try 块运行成功。所以问题在于对 Cognito 的调用。
但是为什么这段代码在几天前可以正常工作时今天却失败了?这是让我非常沮丧的部分。
【问题讨论】:
标签: node.js json aws-lambda amazon-cognito