-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
46 lines (31 loc) · 1.37 KB
/
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
import boto3
connection_handles = [
"CONNECT",
"DISCONNECT"
]
REQUEST_HANDLED = {"statusCode": 200}
# we need to populate this after CloudFormation
SOCKETS_ENDPOINT = "https://gudvhyl103.execute-api.us-east-1.amazonaws.com/latest"
def lambda_handler(event, context):
connection_id = event["requestContext"].get("connectionId")
if event["requestContext"]["eventType"] in connection_handles:
return manage_connection(event,context)
else:
return handle_incoming_ws_message(event, context)
def manage_connection(event, context):
connection_id = event["requestContext"].get("connectionId")
if event["requestContext"]["eventType"] == "CONNECT":
print(f"connected: {connection_id}")
else:
print(f"disconnect: {connection_id}")
return REQUEST_HANDLED
def handle_incoming_ws_message(event, context):
connection_id = event["requestContext"].get("connectionId")
gatewayapi = boto3.client("apigatewaymanagementapi",
endpoint_url=SOCKETS_ENDPOINT)
print(f"SOCKETS_ENDPOINT {SOCKETS_ENDPOINT}")
print(f"connection {connection_id}")
print(f"body {event.get('body', '')}")
gatewayapi.post_to_connection(ConnectionId=connection_id,
Data=event.get("body", ""))
return REQUEST_HANDLED