Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- console.log('Loading function');
- var AWS = require("aws-sdk");
- var docClient = new AWS.DynamoDB.DocumentClient();
- exports.handler = (event, context, callback) => {
- console.log('Received event:', JSON.stringify(event, null, 2));
- event.Records.forEach((record) => {
- console.log('Stream record: ', JSON.stringify(record, null, 2));
- console.log(record.eventID);
- console.log(record.eventName);
- console.log('DynamoDB Record: %j', record.dynamodb);
- if (record.eventName == 'INSERT') {
- //console.log('trigger for deviceId=', record.dynamodb.NewImage.deviceId.S);
- var deviceId = JSON.stringify(record.dynamodb.NewImage.deviceId.S);
- //console.log('trigger for deviceId=', record.dynamodb.NewImage.time.S - 300);
- var startTime = JSON.stringify(record.dynamodb.NewImage.time.S - 300);
- console.log('Querying for readings from ', deviceId + ": " + startTime);
- var params = {
- TableName : "2BEE53",
- KeyConditionExpression: "deviceId = :dev and #ti > :start",
- ExpressionAttributeNames:{
- "#ti": "time"
- },
- ExpressionAttributeValues: {
- ":dev": record.dynamodb.NewImage.deviceId.S,
- ":start": startTime
- }
- };
- docClient.query(params, function(err, data) {
- if (err) {
- console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
- } else {
- console.log("Query succeeded.");
- console.log('Records returned from trigger query=', data.Count);
- data.Items.forEach(function(item) {
- console.log(" -", item.deviceId + ": " + item.time);
- });
- if (data.Count >= 3) {
- var params2 = {
- TableName: "alerts",
- Item:{
- "deviceId": record.dynamodb.NewImage.deviceId.S,
- "time": record.dynamodb.NewImage.time.S,
- "alertType": "movementAlert",
- "acknowledged": "false"
- }
- };
- console.log("Adding a new alert item...");
- docClient.put(params2, function(err2, data2) {
- if (err2) {
- console.error("Unable to add alert. Error JSON:", JSON.stringify(err2, null, 2));
- } else {
- console.log("Added alert:", JSON.stringify(data2, null, 2));
- }
- });
- }
- }
- });
- }
- });
- callback(null, `Successfully processed ${event.Records.length} records.`);
- };
Add Comment
Please, Sign In to add comment