-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.js
85 lines (76 loc) · 1.74 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import AWS from 'aws-sdk'
import { tableName } from './table-name.json'
import { promisifyAll } from 'bluebird';
const docClient = promisifyAll(new AWS.DynamoDB.DocumentClient());
async function create(event) {
const inputBody = event.body && JSON.parse(event.body)
const data = await docClient.putAsync({
TableName: tableName,
Item: {
"title": inputBody.title.trim(),
"done": (inputBody.done || false) ? 1 : 0
}
});
return data;
}
async function update(event) {
const inputBody = event.body && JSON.parse(event.body)
const data = await docClient.updateAsync({
TableName: tableName,
Key: {
"title": inputBody.title.trim()
},
UpdateExpression: "set done=:d",
ExpressionAttributeValues:{
":d": (inputBody.done || false) ? 1 : 0
},
ReturnValues:"ALL_NEW"
})
return data.Attributes;
}
async function list(event) {
const data = await docClient.scanAsync({
TableName: tableName
});
return data.Items;
}
async function remove(event) {
const result = docClient.deleteAsync({
TableName: tableName,
Key:{
"title": decodeURIComponent(event.pathParameters.id)
}
});
return result;
}
export async function todos(event, context, callback) {
let body = {}, statusCode = 200;
try {
switch (event.httpMethod) {
case 'POST':
body = await create(event);
break;
case 'PUT':
body = await update(event);
break;
case 'GET':
body = await list(event);
break;
case 'DELETE':
body = await remove(event);
break;
}
} catch (err) {
statusCode = 400
console.error('error', err)
}
const response = {
statusCode,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true
},
body: JSON.stringify(body),
};
callback(null, response);
}