nig*_*ird 7 javascript amazon-web-services node.js amazon-dynamodb aws-lambda
我编写了一个 node.js lambda 函数,当新记录插入特定表时,该函数基于 dynamodb 流触发。
该函数只接收新事件,过滤插入的记录,然后对于每条记录,使用几个字段从其他表中检索数据。使用此组合数据编写消息并通过 SNS 发送到特定目标 ARN。
该功能正确执行。检索所有相关数据,并发送推送通知。
但是,出于某种原因,该函数似乎为同一个流多次调用,并多次处理新插入的记录。结果是目标设备多次收到相同的推送通知。
我应该将回调放在不同的地方,还是我没有正确调用上下文?
这是函数:
'use strict';
var AWS = require("aws-sdk");
var dynamodb = new AWS.DynamoDB();
var sns = new AWS.SNS();
console.log('Loading function');
exports.handler = (event, context, callback) => {
console.log('Received event:', JSON.stringify(event, null, 2));
event.Records.forEach((record) => {
console.log(record.eventID);
console.log(record.eventName);
console.log('DynamoDB Record: %j', record.dynamodb);
if (record.eventName == 'INSERT') {
var matchId = record.dynamodb.NewImage.eventId.S;
var match_params = {
Key: {
"eventId": {
S: matchId
}
},
TableName: "xxxxxxxxxxx-mobilehub-xxxxxxx-Event"
};
//retrieve the match information from Event table
dynamodb.getItem(match_params, function(err, data) {
var match_description = "";
if (err) {
console.log(err, err.stack);
context.fail('No match event record found in Event table');
} else {
match_description = data.Item.description.S;
var uId = record.dynamodb.NewImage.participantUserId.S; //participantUserId
var user_params = {
Key: {
"userId": {
S: uId
}
},
TableName: "xxxxxxxxxxx-mobilehub-xxxxxxxxx-User"
};
//retrieve the user record from User table
dynamodb.getItem(user_params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
context.fail('Error occurred. See log.');
} else {
console.log(data); // successful response
if (data.length === 0) {
console.log("No User Record Found.");
context.fail('No user found for participantUserId.');
} else {
var deviceARN = data.Item.device_arn.S;
if (deviceARN <= 1) {
console.log("User has not registered their device for push notifications.");
context.fail('User has not registered for notifications');
} else {
var json_message = JSON.stringify({
APNS_SANDBOX: JSON.stringify({
aps: {
alert: "You are playing in an upcoming match " + match_description,
badge: 1,
sound: 'default'
}
})
});
var snsparams = {
Message: json_message,
MessageStructure: 'json',
TargetArn: deviceARN
};
sns.publish(snsparams, function(err, data) {
if (err) {
console.log(err); // an error occurred
context.fail('SNS send failed. See log.');
} else {
console.log(data); // successful response
context.success('Push notification sent to user.');
}
});
}
}
}
});
}
});
}
});
callback(null, `Successfully processed ${event.Records.length} records.`);
};
Run Code Online (Sandbox Code Playgroud)
就我而言,我多次添加了相同的事件源。
引用与 AWS 支持工程师的对话:
使用我的内部工具,我注意到 Lambda 函数 xxxxxx 的事件源:arn:aws:events:my_region:my_acct_id:rule/my_event_target 配置为推送事件源两次。这意味着这可能是您每分钟看到两次调用的原因。请您确认是否为您的 lambda 的 $LATEST 版本配置了两次此事件,并确认它是否是有意的?
我希望这可以拯救其他人:)
| 归档时间: |
|
| 查看次数: |
2784 次 |
| 最近记录: |