|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Web App DynamoDB Sample - CDK Stack.""" |
| 3 | + |
| 4 | +import os |
| 5 | +import aws_cdk as cdk |
| 6 | +from aws_cdk import ( |
| 7 | + Stack, |
| 8 | + aws_lambda as lambda_, |
| 9 | + aws_dynamodb as dynamodb, |
| 10 | + aws_iam as iam, |
| 11 | + CfnOutput, |
| 12 | + Duration, |
| 13 | + RemovalPolicy, |
| 14 | +) |
| 15 | +from constructs import Construct |
| 16 | + |
| 17 | + |
| 18 | +class WebAppDynamoDBStack(Stack): |
| 19 | + def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: |
| 20 | + super().__init__(scope, construct_id, **kwargs) |
| 21 | + |
| 22 | + # DynamoDB Table |
| 23 | + table = dynamodb.Table( |
| 24 | + self, "ItemsTable", |
| 25 | + table_name="cdk-items", |
| 26 | + partition_key=dynamodb.Attribute( |
| 27 | + name="id", |
| 28 | + type=dynamodb.AttributeType.STRING |
| 29 | + ), |
| 30 | + billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST, |
| 31 | + removal_policy=RemovalPolicy.DESTROY, |
| 32 | + ) |
| 33 | + |
| 34 | + # Lambda handler code - must match src/app.py event format |
| 35 | + handler_code = ''' |
| 36 | +import json |
| 37 | +import os |
| 38 | +import boto3 |
| 39 | +from datetime import datetime |
| 40 | +from decimal import Decimal |
| 41 | +
|
| 42 | +class DecimalEncoder(json.JSONEncoder): |
| 43 | + def default(self, obj): |
| 44 | + if isinstance(obj, Decimal): |
| 45 | + return float(obj) |
| 46 | + return super().default(obj) |
| 47 | +
|
| 48 | +ENDPOINT_URL = os.environ.get('LOCALSTACK_HOSTNAME') |
| 49 | +if ENDPOINT_URL: |
| 50 | + ENDPOINT_URL = f"http://{ENDPOINT_URL}:4566" |
| 51 | +dynamodb = boto3.resource('dynamodb', endpoint_url=ENDPOINT_URL) |
| 52 | +TABLE_NAME = os.environ['TABLE_NAME'] |
| 53 | +
|
| 54 | +def handler(event, context): |
| 55 | + method = event.get('httpMethod', 'GET') |
| 56 | + path = event.get('path', '/') |
| 57 | + path_params = event.get('pathParameters') or {} |
| 58 | + body = event.get('body') |
| 59 | + if body and isinstance(body, str): |
| 60 | + try: |
| 61 | + body = json.loads(body) |
| 62 | + except: |
| 63 | + pass |
| 64 | +
|
| 65 | + table = dynamodb.Table(TABLE_NAME) |
| 66 | +
|
| 67 | + if path == '/items' and method == 'GET': |
| 68 | + result = table.scan() |
| 69 | + return response(200, {'items': result.get('Items', [])}) |
| 70 | + elif path == '/items' and method == 'POST': |
| 71 | + if not body: |
| 72 | + return response(400, {'error': 'Invalid request body'}) |
| 73 | + item_id = body.get('id') or f"item-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}" |
| 74 | + item = {'id': item_id, 'name': body.get('name', ''), 'description': body.get('description', ''), |
| 75 | + 'category': body.get('category', 'general'), 'price': Decimal(str(body.get('price', 0))), |
| 76 | + 'createdAt': datetime.utcnow().isoformat(), 'updatedAt': datetime.utcnow().isoformat()} |
| 77 | + table.put_item(Item=item) |
| 78 | + return response(201, item) |
| 79 | + elif path.startswith('/items/') and method == 'GET': |
| 80 | + item_id = path_params.get('id') or path.split('/')[-1] |
| 81 | + result = table.get_item(Key={'id': item_id}) |
| 82 | + item = result.get('Item') |
| 83 | + if not item: |
| 84 | + return response(404, {'error': f'Item {item_id} not found'}) |
| 85 | + return response(200, item) |
| 86 | + elif path.startswith('/items/') and method == 'PUT': |
| 87 | + item_id = path_params.get('id') or path.split('/')[-1] |
| 88 | + result = table.get_item(Key={'id': item_id}) |
| 89 | + if 'Item' not in result: |
| 90 | + return response(404, {'error': f'Item {item_id} not found'}) |
| 91 | + update_expr = 'SET updatedAt = :ua' |
| 92 | + expr_values = {':ua': datetime.utcnow().isoformat()} |
| 93 | + expr_names = {} |
| 94 | + if 'name' in body: |
| 95 | + update_expr += ', #n = :n' |
| 96 | + expr_values[':n'] = body['name'] |
| 97 | + expr_names['#n'] = 'name' |
| 98 | + if 'price' in body: |
| 99 | + update_expr += ', price = :p' |
| 100 | + expr_values[':p'] = Decimal(str(body['price'])) |
| 101 | + update_args = {'Key': {'id': item_id}, 'UpdateExpression': update_expr, |
| 102 | + 'ExpressionAttributeValues': expr_values, 'ReturnValues': 'ALL_NEW'} |
| 103 | + if expr_names: |
| 104 | + update_args['ExpressionAttributeNames'] = expr_names |
| 105 | + result = table.update_item(**update_args) |
| 106 | + return response(200, result.get('Attributes')) |
| 107 | + elif path.startswith('/items/') and method == 'DELETE': |
| 108 | + item_id = path_params.get('id') or path.split('/')[-1] |
| 109 | + result = table.get_item(Key={'id': item_id}) |
| 110 | + if 'Item' not in result: |
| 111 | + return response(404, {'error': f'Item {item_id} not found'}) |
| 112 | + table.delete_item(Key={'id': item_id}) |
| 113 | + return response(204, None) |
| 114 | + return response(404, {'error': 'Not found'}) |
| 115 | +
|
| 116 | +def response(status_code, body): |
| 117 | + resp = {'statusCode': status_code, 'headers': {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'}} |
| 118 | + if body is not None: |
| 119 | + resp['body'] = json.dumps(body, cls=DecimalEncoder) |
| 120 | + return resp |
| 121 | +''' |
| 122 | + |
| 123 | + # Lambda function |
| 124 | + fn = lambda_.Function( |
| 125 | + self, "Handler", |
| 126 | + function_name="cdk-webapp-dynamodb", |
| 127 | + runtime=lambda_.Runtime.PYTHON_3_12, |
| 128 | + handler="index.handler", |
| 129 | + code=lambda_.Code.from_inline(handler_code), |
| 130 | + timeout=Duration.seconds(30), |
| 131 | + memory_size=128, |
| 132 | + environment={ |
| 133 | + "TABLE_NAME": table.table_name, |
| 134 | + }, |
| 135 | + ) |
| 136 | + |
| 137 | + # Grant DynamoDB access |
| 138 | + table.grant_read_write_data(fn) |
| 139 | + |
| 140 | + # Function URL |
| 141 | + fn_url = fn.add_function_url( |
| 142 | + auth_type=lambda_.FunctionUrlAuthType.NONE, |
| 143 | + ) |
| 144 | + |
| 145 | + # Outputs |
| 146 | + CfnOutput(self, "FunctionName", value=fn.function_name) |
| 147 | + CfnOutput(self, "FunctionUrl", value=fn_url.url) |
| 148 | + CfnOutput(self, "TableName", value=table.table_name) |
| 149 | + |
| 150 | + |
| 151 | +app = cdk.App() |
| 152 | +WebAppDynamoDBStack( |
| 153 | + app, "WebAppDynamoDBStack", |
| 154 | + env=cdk.Environment( |
| 155 | + account=os.environ.get("CDK_DEFAULT_ACCOUNT", "000000000000"), |
| 156 | + region=os.environ.get("CDK_DEFAULT_REGION", "us-east-1"), |
| 157 | + ), |
| 158 | +) |
| 159 | +app.synth() |
0 commit comments