forked from utrains/Serverless-lambda-function
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
157 lines (131 loc) · 4.46 KB
/
lambda_function.py
File metadata and controls
157 lines (131 loc) · 4.46 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
import boto3
import json
from custom_encoder import CustomEncoder
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
#define our dynamodb table
dynamodbTableName = 'userseverless'
#define our dynamo clients
dynamodb = boto3.resource('dynamodb')
#define our table
table = dynamodb.Table(dynamodbTableName)
#define our methods
getMethod = 'GET'
postMethod = 'POST'
putMethod = 'PUT'
deleteMethod = 'DELETE'
#define our Paths
healthPath = '/health'
productPath = '/user'
productsPath = '/users'
# entry point for our lambda function
def lambda_handler(event, context):
logger.info(event) #log the request event to see how the request looks like
httpMethod = event['httpMethod'] #extract the http method from our event object
path = event['path'] #extract the path
if httpMethod == getMethod and path == healthPath:
response = buildResponse(200)
elif httpMethod == getMethod and path == productPath:
response = getProduct(event['queryStringParameters']['id'])
elif httpMethod == getMethod and path == productsPath:
response = getProducts()
elif httpMethod == postMethod and path == productPath:
response = saveProduct(json.loads(event['body']))
elif httpMethod == putMethod and path == productPath:
requestBody = json.loads(event['body'])
response = modifyProduct(requestBody)
elif httpMethod == deleteMethod and path == productPath:
requestBody = json.loads(event['body'])
response = deleteProduct(requestBody['id'])
else:
response = buildResponse(404, 'Not found')
return response
def getProduct(productId):
try:
response = table.get_item(
Key={
'id': 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. I am just gonna log it out here')
def getProducts():
try:
response = table.scan()
result = response['Items']
while 'LastEvaluatedKey' 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. I am just gonna log it out here')
def saveProduct(requestBody):
try:
table.put_item(Item=requestBody)
body = {
'Operation': 'SAVE',
'Message': 'SUCCESS',
'Item': requestBody
}
return buildResponse(200, body)
except:
logger.exception('sorry your item wasnt ')
def modifyProduct(event):
try:
response = table.update_item(
Key={
'id': event['id']
},
UpdateExpression='SET fname=:pn, lname= :pnum ,username=:pb, email=:d , avatar= :a',
ExpressionAttributeValues={
':pn': event['fname'],
':pnum':event['lname'],
':pb':event['username'],
':d':event['email'],
':a': event['avatar'],
},
ReturnValues='UPDATED_NEW'
)
body = {
'Operation': 'UPDATE',
'Message': 'SUCCESS',
'UpdateAttributes': response
}
return buildResponse(200, body)
except:
logger.exception('Do your custom error handling here. I am just gonna log it out here')
def deleteProduct(productId):
try:
response = table.delete_item(
Key={
'id': productId
},
ReturnValues='ALL_OLD'
)
body = {
'Operation': 'DELETE',
'Message': 'SUCCESS',
'deletedItem': response
}
return buildResponse(200, body)
except:
logger.exception('Do your custom error handling here. I am just gonna log it out here')
def buildResponse(statusCode, body=None):
response = {
'statusCode': statusCode,
'headers': {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}
}
if body is not None:
response['body'] = json.dumps(body, cls=CustomEncoder)
return response