Created
December 10, 2017 10:35
-
-
Save tonkatsu7/2046b0896e375504f01c4b397b1687e5 to your computer and use it in GitHub Desktop.
DynamoDB trigger that inserts a new record into a table called alerts if 3 or more records received in source table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.`); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment