AWS Lambda 优化实战:Claude Code 开发指南
借助 Claude Code 高效编写 AWS Lambda 函数,涵盖 API Gateway、DynamoDB 联动、CDK IaC 与本地调试的完整流程。
用 Claude Code 加速 AWS Lambda 开发
AWS Lambda 是一款事件驱动的 Serverless 计算服务,能和 API Gateway、S3、DynamoDB 等 AWS 服务紧密联动,快速搭建可弹性扩展的后端。借助 Claude Code,你可以更高效地写出符合 Lambda 实现模式的代码,IaC 脚本也能一并搞定。
Lambda 函数的基本设计
> 用 TypeScript 帮我写一个 Lambda 函数,
> 结构上要能处理来自 API Gateway 的请求。
// src/handlers/api.ts
import {
APIGatewayProxyEvent,
APIGatewayProxyResult,
Context,
} from 'aws-lambda';
export const handler = async (
event: APIGatewayProxyEvent,
context: Context
): Promise<APIGatewayProxyResult> => {
const { httpMethod, path, body, queryStringParameters } = event;
try {
switch (`${httpMethod} ${path}`) {
case 'GET /users':
return await getUsers(queryStringParameters);
case 'POST /users':
return await createUser(JSON.parse(body || '{}'));
case 'GET /users/{id}':
const id = event.pathParameters?.id;
return await getUser(id!);
default:
return response(404, { error: 'Not Found' });
}
} catch (error) {
console.error('Lambda error:', error);
return response(500, { error: 'Internal Server Error' });
}
};
function response(statusCode: number, body: object): APIGatewayProxyResult {
return {
statusCode,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify(body),
};
}
async function getUsers(params: any) {
// 从 DynamoDB 获取用户列表
return response(200, { users: [] });
}
async function createUser(data: any) {
return response(201, { id: 'new-user-id', ...data });
}
async function getUser(id: string) {
return response(200, { id, name: 'User' });
}
与 DynamoDB 联动
> 用 DynamoDB 封装一组 CRUD 的工具函数。
// src/lib/dynamodb.ts
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import {
DynamoDBDocumentClient,
GetCommand,
PutCommand,
QueryCommand,
DeleteCommand,
} from '@aws-sdk/lib-dynamodb';
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
const TABLE_NAME = process.env.TABLE_NAME!;
export async function getItem<T>(pk: string, sk: string): Promise<T | null> {
const { Item } = await docClient.send(
new GetCommand({
TableName: TABLE_NAME,
Key: { PK: pk, SK: sk },
})
);
return (Item as T) || null;
}
export async function putItem(item: Record<string, any>): Promise<void> {
await docClient.send(
new PutCommand({
TableName: TABLE_NAME,
Item: {
...item,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
})
);
}
export async function queryItems<T>(
pk: string,
skPrefix?: string
): Promise<T[]> {
const params: any = {
TableName: TABLE_NAME,
KeyConditionExpression: skPrefix
? 'PK = :pk AND begins_with(SK, :sk)'
: 'PK = :pk',
ExpressionAttributeValues: { ':pk': pk },
};
if (skPrefix) {
params.ExpressionAttributeValues[':sk'] = skPrefix;
}
const { Items } = await docClient.send(new QueryCommand(params));
return (Items as T[]) || [];
}
用 AWS CDK 定义基础设施
> 用 CDK 定义一套 Lambda + API Gateway + DynamoDB 的 Stack。
// lib/api-stack.ts
import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Construct } from 'constructs';
export class ApiStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// DynamoDB 表
const table = new dynamodb.Table(this, 'MainTable', {
partitionKey: { name: 'PK', type: dynamodb.AttributeType.STRING },
sortKey: { name: 'SK', type: dynamodb.AttributeType.STRING },
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
// Lambda 函数
const apiHandler = new NodejsFunction(this, 'ApiHandler', {
entry: 'src/handlers/api.ts',
handler: 'handler',
runtime: lambda.Runtime.NODEJS_20_X,
architecture: lambda.Architecture.ARM_64,
memorySize: 256,
timeout: cdk.Duration.seconds(30),
environment: {
TABLE_NAME: table.tableName,
NODE_OPTIONS: '--enable-source-maps',
},
bundling: {
minify: true,
sourceMap: true,
},
});
table.grantReadWriteData(apiHandler);
// API Gateway
const api = new apigateway.RestApi(this, 'Api', {
restApiName: 'My API',
deployOptions: { stageName: 'v1' },
});
const users = api.root.addResource('users');
users.addMethod('GET', new apigateway.LambdaIntegration(apiHandler));
users.addMethod('POST', new apigateway.LambdaIntegration(apiHandler));
}
}
本地开发与测试
# 用 SAM 在本地启动
sam local start-api
# 单独测试某个函数
sam local invoke ApiHandler -e events/get-users.json
# 使用 CDK 部署
cdk deploy --require-approval never
总结
把 AWS Lambda 和 Claude Code 结合起来,从 Serverless 架构设计到 IaC 编写都能顺畅推进。想了解更多可以参考 AWS 部署指南 和 Serverless 函数指南。
深入阅读请参阅 AWS Lambda 官方文档。
#Claude Code
#AWS Lambda
#serverless
#AWS
#云计算
M
本文作者
Masa
深度使用 Claude Code 的工程师。运营 claudecode-lab.com——一个涵盖 10 种语言、超过 2,000 页内容的科技媒体。
相关文章
Use Cases
用 Claude Code 加速个人项目开发【附实战案例】
详解如何用 Claude Code 大幅提升个人项目的开发速度。包含从创意到上线的完整实战案例和工作流。
Use Cases
如何用 Claude Code 自动化代码重构
详解如何利用 Claude Code 高效完成代码重构自动化。包含实用提示词和真实项目中的重构模式。
Use Cases
Complete CORS Configuration Guide:Claude Code 实战指南
了解complete cors configuration guide:Claude Code 实战. 包含实用技巧和代码示例。