111 lines
3.3 KiB
Python
111 lines
3.3 KiB
Python
import json
|
|
import function_a
|
|
import function_b
|
|
|
|
|
|
def lambda_handler(event, context):
|
|
"""
|
|
AWS Lambda handler that routes to function_a or function_b
|
|
|
|
Expected event structure:
|
|
{
|
|
"function_name": "function_a" or "function_b",
|
|
"text_parameter": "your string here"
|
|
}
|
|
"""
|
|
try:
|
|
# DEBUG: Log the entire event
|
|
print(f"Received event: {json.dumps(event)}")
|
|
|
|
# Handle different event sources
|
|
body = None
|
|
|
|
# Check if body exists and is a string (API Gateway)
|
|
if 'body' in event:
|
|
if event['body'] is None:
|
|
return {
|
|
'statusCode': 400,
|
|
'body': json.dumps({'error': 'Request body is empty'})
|
|
}
|
|
|
|
if isinstance(event['body'], str):
|
|
# Try to parse JSON
|
|
try:
|
|
body = json.loads(event['body'])
|
|
except json.JSONDecodeError as e:
|
|
return {
|
|
'statusCode': 400,
|
|
'body': json.dumps({
|
|
'error': 'Invalid JSON in request body',
|
|
'details': str(e),
|
|
'received': event['body'][:100] # First 100 chars
|
|
})
|
|
}
|
|
else:
|
|
body = event['body']
|
|
else:
|
|
# Direct invocation (no body wrapper)
|
|
body = event
|
|
|
|
print(f"Parsed body: {json.dumps(body)}")
|
|
|
|
# Get parameters
|
|
function_name = body.get('function_name')
|
|
text_parameter = body.get('text_parameter')
|
|
|
|
# Validate inputs
|
|
if not function_name:
|
|
return {
|
|
'statusCode': 400,
|
|
'body': json.dumps({'error': 'function_name is required'})
|
|
}
|
|
|
|
if not text_parameter:
|
|
return {
|
|
'statusCode': 400,
|
|
'body': json.dumps({'error': 'text_parameter is required'})
|
|
}
|
|
|
|
# Route to the appropriate function
|
|
if function_name == 'function_a':
|
|
result = function_a.execute(text_parameter)
|
|
elif function_name == 'function_b':
|
|
result = function_b.execute(text_parameter)
|
|
else:
|
|
return {
|
|
'statusCode': 400,
|
|
'body': json.dumps({'error': f'Unknown function: {function_name}. Use "function_a" or "function_b"'})
|
|
}
|
|
|
|
# Return success response
|
|
return {
|
|
'statusCode': 200,
|
|
'body': json.dumps({
|
|
'message': 'Success',
|
|
'result': result
|
|
})
|
|
}
|
|
|
|
except Exception as e:
|
|
print(f"Error: {str(e)}")
|
|
import traceback
|
|
print(traceback.format_exc())
|
|
return {
|
|
'statusCode': 500,
|
|
'body': json.dumps({
|
|
'error': str(e),
|
|
'type': type(e).__name__
|
|
})
|
|
}
|
|
|
|
|
|
# For local testing
|
|
if __name__ == "__main__":
|
|
# Test event
|
|
test_event = {
|
|
'function_name': 'function_a',
|
|
'text_parameter': 'Hello from Lambda!'
|
|
}
|
|
|
|
result = lambda_handler(test_event, None)
|
|
print(json.dumps(result, indent=2)) |