Guest User

Untitled

a guest
Dec 12th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.97 KB | None | 0 0
  1. console.log('Loading function');
  2.  
  3. var AWS = require("aws-sdk");
  4. var docClient = new AWS.DynamoDB.DocumentClient();
  5.  
  6. exports.handler = (event, context, callback) => {
  7. console.log('Received event:', JSON.stringify(event, null, 2));
  8. event.Records.forEach((record) => {
  9. console.log('Stream record: ', JSON.stringify(record, null, 2));
  10. console.log(record.eventID);
  11. console.log(record.eventName);
  12. console.log('DynamoDB Record: %j', record.dynamodb);
  13.  
  14. if (record.eventName == 'INSERT') {
  15. //console.log('trigger for deviceId=', record.dynamodb.NewImage.deviceId.S);
  16. var deviceId = JSON.stringify(record.dynamodb.NewImage.deviceId.S);
  17. //console.log('trigger for deviceId=', record.dynamodb.NewImage.time.S - 300);
  18. var startTime = JSON.stringify(record.dynamodb.NewImage.time.S - 300);
  19.  
  20. console.log('Querying for readings from ', deviceId + ": " + startTime);
  21.  
  22. var params = {
  23. TableName : "2BEE53",
  24. KeyConditionExpression: "deviceId = :dev and #ti > :start",
  25. ExpressionAttributeNames:{
  26. "#ti": "time"
  27. },
  28. ExpressionAttributeValues: {
  29. ":dev": record.dynamodb.NewImage.deviceId.S,
  30. ":start": startTime
  31. }
  32. };
  33.  
  34. docClient.query(params, function(err, data) {
  35. if (err) {
  36. console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
  37. } else {
  38. console.log("Query succeeded.");
  39. console.log('Records returned from trigger query=', data.Count);
  40. data.Items.forEach(function(item) {
  41. console.log(" -", item.deviceId + ": " + item.time);
  42. });
  43. if (data.Count >= 3) {
  44. var params2 = {
  45. TableName: "alerts",
  46. Item:{
  47. "deviceId": record.dynamodb.NewImage.deviceId.S,
  48. "time": record.dynamodb.NewImage.time.S,
  49. "alertType": "movementAlert",
  50. "acknowledged": "false"
  51. }
  52. };
  53. console.log("Adding a new alert item...");
  54. docClient.put(params2, function(err2, data2) {
  55. if (err2) {
  56. console.error("Unable to add alert. Error JSON:", JSON.stringify(err2, null, 2));
  57. } else {
  58. console.log("Added alert:", JSON.stringify(data2, null, 2));
  59. }
  60. });
  61. }
  62. }
  63. });
  64. }
  65. });
  66. callback(null, `Successfully processed ${event.Records.length} records.`);
  67. };
Add Comment
Please, Sign In to add comment