-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
177 lines (138 loc) · 4.92 KB
/
Copy pathlambda_function.py
File metadata and controls
177 lines (138 loc) · 4.92 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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import boto3
import json
import logging
from custom_encoder import CustomEncoder
logger = logging.getLogger()
logger.setLevel(logging.INFO)
dynamo_tabe_name = 'YOUR_TABLE_NAME'
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(dynamo_tabe_name)
# Available Methods:
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 = Response(200, body = {'message': 'Health check passed'})
elif HTTPMethod == GetMethod and path == ProductPath:
response = getProduct(event['queryStringParameters']['productID'])
elif HTTPMethod == GetMethod and path == ProductsPath:
response = getProducts()
elif HTTPMethod == PostMethod and path == ProductPath:
data = json.loads(event['body'])
response = saveProduct(data)
elif HTTPMethod == PatchMethod and path == ProductPath:
data = json.loads(event['body'])
response = modifyProduct(data['productID'], data['updateKey'], data['updateValue'])
elif HTTPMethod == DeleteMethod and path == ProductPath:
data = json.loads(event['body'])
response = deleteProduct(data['productID'])
else:
response = Response(404, 'Method Not Found')
return response
def Response(status_code, body=None):
response = {
"isBase64Encoded": False,
'statusCode': status_code,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
}
if body is not None:
response['body'] = json.dumps(body, cls=CustomEncoder)
return response
# Get a specific product
def getProduct(productId):
try:
result = table.get_item(
Key = {
'productID': productId
}
)
if 'Item' in result:
return Response(200, result['Item'])
else:
return Response(404, {'Message': f'ProductID search: {productId} not found'})
except ValueError as ve:
logger.exception(f"An error occurred while fetching the item: {ve}")
return Response(500, {'Message': f'An error occurred while fetching the item: {ve}'})
# Get all products in inventory.
def getProducts():
try:
response = table.scan()
results = response['Items']
while 'LastEvaluatedKey' in response:
response = table.scam(ExclusiveStartKey=response['LastEvaluatedKey'])
results.extend(response['Items'])
body = {
'products': results
}
return Response(200, body)
except Exception as e:
logger.exception(f'A exception ocurred: {e}')
return Response(500, {'Message': 'An error occurred', "Error": f"{e}"})
def saveProduct(data):
try:
table.put_item(Item=data)
body = {
'Operation': 'SAVE',
'Message': 'SUCCESS',
'Item': data
}
return Response(200, body)
except Exception as e:
logger.exception(f'An error occurred while saving the product: {e}')
return Response(500, {'Message': 'An error occurred while saving the product', "Error": f"{e}"})
def modifyProduct(productId, updateKey, updateValue):
try:
response = table.update_item(
Key = {
'productID': productId
},
UpdateExpression = f'set {updateKey} = :value',
ExpressionAttributeValues = {
':value': updateValue
},
ReturnValues = 'UPDATED_NEW'
)
body = {
'Operation': 'UPDATE',
'MESSAGE': 'SUCCESS',
'UpdatedAttributes': response
}
return Response(200, body)
except KeyError as ke:
logger.exception(f'Missing key: {ke}')
return Response(400, {'MESSAGE': f'Missing key: {ke}'})
except Exception as e:
logger.exception(f'A exception ocurred: {e}')
return Response(500, {'MESSAGE': f'A exception ocurred: {e}'})
def deleteProduct(productId):
try:
response = table.delete_item(
Key = {
'productID': productId
},
ReturnValues = 'ALL_OLD'
)
body = {
'Operation': 'DELETE',
'MESSAGE': 'SUCCESS',
'DeletedItem': response
}
return Response(200, body)
except KeyError as ke:
if "NotFound" in str(ke):
logger.exception(f'ProductID: {id} Not Found')
return Response(404, {'MESSAGE': f'ProductID: {id} Not Found'})
except Exception as e:
logger.exception(f'A exception ocurred: {e}')
return Response(500, {'MESSAGE': f'A exception ocurred: {e}'})