-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
137 lines (122 loc) · 3.98 KB
/
lambda_function.py
File metadata and controls
137 lines (122 loc) · 3.98 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import boto3
import json
from custom_encoder import CustomEncoder
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
dynamodbTableName = 'product-inventory'
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(dynamodbTableName)
getMethod = 'GET'
postMethod = 'POST'
patchMethod = 'PATCH'
deleteMethod = 'DELETE'
healthPath = '/health'
productPath = '/product'
productsPath = '/products'
def lambda_handler(event, context):
logger.info(event)
httpMethod = event['httpMethod']
path = event['path']
if httpMethod == getMethod and path == healthPath:
response = buildResponse(200)
elif httpMethod == getMethod and path == productPath:
#confirm here:
response = getProduct(event['queryStringParameters']['productId'])
elif httpMethod == getMethod and path == productsPath:
response = getProducts()
elif httpMethod == postMethod and path == productPath:
response = saveProduct(json.loads(event['body']))
elif httpMethod == patchMethod and path == productPath:
requestBody = json.loads(event['body'])
response = modifyProduct(requestBody['productId'], requestBody['updateKey'], requestBody['updateValue'])
elif httpMethod == deleteMethod and path == productPath:
requestBody = json.loads(event['body'])
response = deleteProduct(requestBody['productId'])
else:
response = buildResponse(404, 'Not Found')
return response
def getProduct(productId):
try:
response = table.get_item(
Key={
'productId': productId
}
)
if 'Item' in response:
return buildResponse(200, response['Item'])
else:
return buildResponse(404, {'Message': 'ProductId: %s not found' % productId})
except:
logger.exception('Do your custom error handling here!')
def getProducts():
try:
response = table.scan()
result = response["Items"]
while "LastEvaluateKey" in response:
response = table.scan(ExclusiveStartKey=response["LastEvaluatedKey"])
result.extend(response["Items"])
body = {
"products": result
}
return buildResponse(200, body)
except:
logger.exception("Do your custom error handling here!")
def saveProduct(requestBody):
try:
table.put_item(Item=requestBody)
body = {
"Operation": "SAVE",
"Message": "SUCCESS",
"Item": requestBody
}
return buildResponse(200, body)
except:
logger.exception("Do your custom error handling here!")
def modifyProduct(productId, updateKey, updateValue):
try:
response = table.update_item(
Key={
"productId": productId
},
UpdateExpression="set {0} = :value".format(updateKey),
ExpressionAttributeValues={
":value": updateValue
},
ReturnValues="UPDATED_NEW"
)
body = {
"Operation": "UPDATE",
"Message": "SUCCESS",
"UpdatedAttributes": response
}
return buildResponse(200, body)
except:
logger.exception("Do your custom error handling here!")
def deleteProduct(productId):
try:
response = table.delete_item(
Key={
"productId": productId
},
ReturnValues="ALL_OLD"
)
body = {
"Operation": "DELETE",
"Message": "SUCCESS",
"deltedItem": response
}
return buildResponse(200, body)
except:
logger.exception("Do your custom error handling here!")
def buildResponse(statusCode, body=None):
response = {
'statusCode': statusCode,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
}
if body is not None:
response['body'] = json.dumps(body, cls=CustomEncoder)
return response