def lambda_handler()

in functions/source/websocket-connection/lambda_function.py [0:0]


def lambda_handler(event, context):
    """

    The function is called when the route selection expression
    $request.body.service matches "$connect" or "$disconnect" or "transcribe":

    """

    # Log the values received in the event and context arguments
    logger.info('message event: ' + json.dumps(event, indent=2))
    routeKey = event['requestContext']['routeKey']
    connectionId = event['requestContext']['connectionId']
    if routeKey == '$connect':
        # if client is registered to the connection, connection id is inserted into the table
        insert_to_table(connectionId)
        msg = 'connection established'
    elif routeKey == 'transcribe':
        # receive transactionId from the message body and set transactionId against connectionId in the table
        body = json.loads(event['body'])
        transactionId = body.get('transactionId')
        update_table(connectionId,transactionId)
        msg = 'sent transcribe message'
    elif routeKey == '$disconnect':
        # if client is disconnected, delete the record from the table
        delete_from_table(connectionId)
        msg = 'disconnected'
    elif routeKey == '$default':
        # if client is on default route
        msg = 'sent default message'
        wsclient = boto3.client('apigatewaymanagementapi',endpoint_url = os.environ['WEBSOCKET_URL'])
        response = wsclient.post_to_connection(
            Data=json.dumps(msg),
            ConnectionId=connectionId
        )
    elif routeKey == 'delete':
        # if client is on delete route
        msg = 'deleted files from s3 and records from tables'
        body = json.loads(event['body'])
        transactionId = body.get('transactionId')
        single_files_bucket = os.environ["SINGLE_FILES_S3_BUCKET"]
        merged_files_bucket = os.environ["MERGED_FILES_S3_BUCKET"]
        # transactionId = '0da9e59b-c092-44f7-976d-04fde7e9fd82'
        try:
            delete_from_transcripts_table(transactionId)
            delete_from_keywords_table(transactionId)
            delete_from_entities_table(transactionId)
        except Exception as e:
            print("Exception while deleting DynanmoDB .",str(e))
        try:
            delete_from_s3(single_files_bucket,transactionId)
            delete_from_s3(merged_files_bucket,transactionId)
        except Exception as e:
            print("Exception while deleting S3 files.",str(e))
        wsclient = boto3.client('apigatewaymanagementapi',endpoint_url = os.environ['WEBSOCKET_URL'])
        response = wsclient.post_to_connection(
            Data=json.dumps(msg),
            ConnectionId=connectionId
        )
    return {
        'statusCode': 200,
        'body': json.dumps(msg)
    }