[ PROMPT_NODE_23744 ]
aws-serverless
[ SKILL_DOCUMENTATION ]
# AWS Serverless
## 模式
### Lambda 处理程序模式
具有错误处理功能的规范 Lambda 函数结构
**适用场景**: ['任何 Lambda 函数实现', 'API 处理程序、事件处理器、定时任务']
python
javascript
// Node.js Lambda 处理程序
// handler.js
// 在处理程序外部初始化(在多次调用间复用)
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb');
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
// 处理程序函数
exports.handler = async (event, context) => {
// 可选:不等待事件循环清空 (Node.js)
context.callbackWaitsForEmptyEventLoop = false;
try {
// 根据事件源解析输入
const body = typeof event.body === 'string'
? JSON.parse(event.body)
: event.body;
// 业务逻辑
const result = await processRequest(body);
// 返回兼容 API Gateway 的响应
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(result)
};
} catch (error) {
console.error('Error:', JSON.stringify({
error: error.message,
stack: error.stack,
requestId: context.awsRequestId
}));
return {
statusCode: error.statusCode || 500,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
error: error.message || 'Internal server error'
})
};
}
};
async function processRequest(data) {
// 在此编写业务逻辑
const result = await docClient.send(new GetCommand({
TableName: process.env.TABLE_NAME,
Key: { id: data.id }
}));
return result.Item;
}
python
# Python Lambda 处理程序
# handler.py
import json
import os
import logging
import boto3
from botocore.exceptions import ClientError
# 在处理程序外部初始化(在多次调用间复用)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['TABLE_NAME'])
def handler(event, context):
try:
# 解析输入
### API Gateway 集成模式
REST API 和 HTTP API 与 Lambda 的集成
**适用场景**: ['构建由 Lambda 支持的 REST API', '需要为函数提供 HTTP 端点']
javascript
yaml
# template.yaml (SAM)
AWSTemplateFormatVersion: '2010-09-09'
T