-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.js
62 lines (58 loc) · 1.93 KB
/
handler.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
'use strict';
var AWS = require("aws-sdk");
const config = require('./conf/config.json');
const docClient = new AWS.DynamoDB.DocumentClient();
const tableName = config['tableName'];
const counterName = config['counterName'];
module.exports.counter = (event, context, callback) => {
const params = {
TableName: tableName,
Key: {
"name": counterName
},
UpdateExpression: "set num = num + :val",
ConditionExpression: "attribute_exists(num)",
ExpressionAttributeValues:{
":val": 1
},
ReturnValues:"UPDATED_NEW"
};
docClient.update(params, function(err, data) {
var response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*" // Required for CORS support to work
},
body: JSON.stringify({
count: 0
})
};
if (err) {
console.log("Unable to update item. Error JSON:", JSON.stringify(err, null, 2));
const params_init = {
TableName: tableName,
Item:{
"name": counterName,
"num": 1
}
};
docClient.put(params_init, function(err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
response.statusCode = 500;
} else {
console.log("Added item:", JSON.stringify(data, null, 2));
response.body = JSON.stringify({
count: 1
});
}
});
} else {
console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));
response.body = JSON.stringify({
count: data.Attributes.num
});
}
callback(null, response);
});
};