|
| 1 | +from aws_lambda_powertools.utilities.data_classes import event_source |
| 2 | +from aws_lambda_powertools.utilities.data_classes.appsync_resolver_event import ( |
| 3 | + AppSyncIdentityCognito, |
| 4 | + AppSyncResolverEvent, |
| 5 | +) |
| 6 | +from aws_lambda_powertools.utilities.typing import LambdaContext |
| 7 | + |
| 8 | + |
| 9 | +@event_source(data_class=AppSyncResolverEvent) |
| 10 | +def lambda_handler(event: AppSyncResolverEvent, context: LambdaContext): |
| 11 | + # Access the AppSync event details |
| 12 | + type_name = event.type_name |
| 13 | + field_name = event.field_name |
| 14 | + arguments = event.arguments |
| 15 | + source = event.source |
| 16 | + |
| 17 | + print(f"Resolving field '{field_name}' for type '{type_name}'") |
| 18 | + print(f"Arguments: {arguments}") |
| 19 | + print(f"Source: {source}") |
| 20 | + |
| 21 | + # Check if the identity is Cognito-based |
| 22 | + if isinstance(event.identity, AppSyncIdentityCognito): |
| 23 | + user_id = event.identity.sub |
| 24 | + username = event.identity.username |
| 25 | + print(f"Request from Cognito user: {username} (ID: {user_id})") |
| 26 | + else: |
| 27 | + print("Request is not from a Cognito-authenticated user") |
| 28 | + |
| 29 | + if type_name == "Merchant" and field_name == "locations": |
| 30 | + page = arguments.get("page", 1) |
| 31 | + size = arguments.get("size", 10) |
| 32 | + name_filter = arguments.get("name") |
| 33 | + |
| 34 | + # Here you would typically fetch locations from a database |
| 35 | + # This is a mock implementation |
| 36 | + locations = [ |
| 37 | + {"id": "1", "name": "Location 1", "address": "123 Main St"}, |
| 38 | + {"id": "2", "name": "Location 2", "address": "456 Elm St"}, |
| 39 | + {"id": "3", "name": "Location 3", "address": "789 Oak St"}, |
| 40 | + ] |
| 41 | + |
| 42 | + # Apply name filter if provided |
| 43 | + if name_filter: |
| 44 | + locations = [loc for loc in locations if name_filter.lower() in loc["name"].lower()] |
| 45 | + |
| 46 | + # Apply pagination |
| 47 | + start = (page - 1) * size |
| 48 | + end = start + size |
| 49 | + paginated_locations = locations[start:end] |
| 50 | + |
| 51 | + return { |
| 52 | + "items": paginated_locations, |
| 53 | + "totalCount": len(locations), |
| 54 | + "nextToken": str(page + 1) if end < len(locations) else None, |
| 55 | + } |
| 56 | + else: |
| 57 | + raise Exception(f"Unhandled field: {field_name} for type: {type_name}") |
0 commit comments