forked from nicjansma/dht-logger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda.js
79 lines (66 loc) · 1.92 KB
/
lambda.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//
// Creates a DynamoDB row with your IoT data.
// By Nic Jansma http://nicj.net
//
// https://github.com/nicjansma/dht-logger/
//
// Based on: https://snowulf.com/2015/08/05/tutorial-aws-api-gateway-to-lambda-to-dynamodb/
//
//
// Imports
//
var doc = require("dynamodb-doc");
//
// Constants
//
var TABLE_NAME = "iot";
var dynamodb = new doc.DynamoDB();
exports.handler = function(event, context) {
console.log("Request received:\n", JSON.stringify(event));
console.log("Context received:\n", JSON.stringify(context));
var dateTime = new Date().getTime();
var item = {
"device": event.device,
"time": dateTime
};
if (typeof event.coreid !== "undefined") {
item.deviceId = event.coreid;
}
if (typeof event.event !== "undefined") {
item.event = event.event;
}
// parse data payload
var data;
// if there is a 'data' property, it's possibly from a Particle Webhook, and we should use those values
if (typeof event.data !== "undefined" && typeof event.published_at !== "undefined") {
try {
data = JSON.parse(event.data);
} catch (e) {
return context.fail("Failed to parse data JSON");
}
} else {
data = event;
}
// copy data properties over to DynamoDB item
for (var key in data) {
if (data.hasOwnProperty(key) &&
typeof data[key] !== "undefined" &&
data[key] !== null &&
data[key] !== "") {
item[key] = data[key];
}
}
console.log("Item:\n", item);
// Put into DynamoDB!
dynamodb.putItem({
"TableName": TABLE_NAME,
"Item": item
}, function(err, data) {
if (err) {
context.fail("ERROR: Dynamo failed: " + err);
} else {
console.log("Dynamo Success: " + JSON.stringify(data, null, " "));
context.succeed({ success: true });
}
});
}