-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbackend_lambda_function.py
72 lines (61 loc) · 1.9 KB
/
backend_lambda_function.py
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
import boto3
import json
def lambda_handler(event, context):
dynamodb = boto3.client("dynamodb")
table_name = "minimal-backend-table"
table_scan = dynamodb.scan(TableName=table_name)
# check for POST, otherwise default to GET
if event["httpMethod"] == "POST":
request = json.loads(event["body"])
if request["operation"] == "delete":
dynamodb.delete_item(
TableName=table_name,
Key={
"id": {
"N": request["id"]
}
}
)
elif request["operation"] == "update":
dynamodb.update_item(
TableName=table_name,
Key={
"id": {
"N": request["id"]
}
},
UpdateExpression="SET #n = :new_name",
ExpressionAttributeNames={"#n": "name"},
ExpressionAttributeValues={
":new_name": {
"S": request["name"]
}
}
)
else:
table_item_ids = [
int(item["id"]["N"])
for item in table_scan["Items"]
]
table_item_ids.append(0)
new_id = max(table_item_ids) + 1
dynamodb.put_item(
TableName=table_name,
Item={
"id": {"N": str(new_id)},
"name": {"S": request["name"]}
}
)
table_scan = dynamodb.scan(TableName=table_name)
items = [
{"id": item["id"]["N"], "name": item["name"]["S"]}
for item in table_scan["Items"]
]
response = {
"statusCode": 200,
"headers": {
'Access-Control-Allow-Origin': '*',
},
"body": json.dumps(items)
}
return response