Lambda 函数模式
// AWS Lambda 处理器(Node.js)
export const handler = async (event, context) => {
// 针对 API Gateway
if (event.httpMethod) {
const body = JSON.parse(event.body || '{}');
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'OK', data: body })
};
}
// 针对 SQS 批量处理
if (event.Records) {
const failures = [];
for (const record of event.Records) {
try {
await processMessage(JSON.parse(record.body));
} catch (err) {
failures.push({ itemIdentifier: record.messageId });
}
}
return { batchItemFailures: failures }; // 部分批次响应
}
};
# SAM 模板
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs20.x
MemorySize: 256
Timeout: 30
Events:
Api:
Type: Api
Properties:
Path: /users
Method: post