如何在Lambda函数中访问GraphQL模型生成的DynamoDB并执行操作
实现Lambda查询与更新Amplify生成的DynamoDB User表方案
前置准备
- 确保Lambda执行角色已配置User表的
dynamodb:GetItem、dynamodb:UpdateItem权限,通过Amplify CLI可快速配置:执行amplify function update选择对应Lambda函数,按提示开启DynamoDB读写权限并选中User表即可 - AWS SDK v3默认已在Lambda Node.js运行时预装,本地调试可自行安装对应依赖包
核心实现代码
const { DynamoDBClient, GetItemCommand, UpdateItemCommand } = require("@aws-sdk/client-dynamodb"); const { marshall, unmarshall } = require("@aws-sdk/util-dynamodb"); // 替换为你的实际User表名,可在Amplify控制台或DynamoDB控制台查看 const TABLE_NAME = "User-<你的环境名>-<随机后缀>"; const client = new DynamoDBClient({ region: process.env.AWS_REGION }); exports.handler = async (event, context) => { // DynamoDB触发器场景下处理触发事件记录,非触发器场景可删除该段逻辑 if (event.Records) { event.Records.forEach((record) => { console.log("触发事件ID:", record.eventID); console.log("触发事件类型:", record.eventName); console.log("变更记录:", unmarshall(record.dynamodb.NewImage)); }); } // 从event中获取待操作的用户ID和要更新的coins数值 const { userId, updateCoins } = event; if (!userId) { throw new Error("缺少必填参数userId"); } try { // 1. 查询指定用户数据 const getParams = { TableName: TABLE_NAME, Key: marshall({ id: userId }) }; const getRes = await client.send(new GetItemCommand(getParams)); if (!getRes.Item) { throw new Error("对应用户不存在"); } const userData = unmarshall(getRes.Item); console.log("查询到的用户数据:", userData); // 2. 更新用户coins数值(示例为累加逻辑,可按需调整) if (updateCoins !== undefined) { const updateParams = { TableName: TABLE_NAME, Key: marshall({ id: userId }), UpdateExpression: "SET coins = :newCoins", ExpressionAttributeValues: marshall({ ":newCoins": (userData.coins || 0) + updateCoins }), ReturnValues: "ALL_NEW" }; const updateRes = await client.send(new UpdateItemCommand(updateParams)); const updatedUser = unmarshall(updateRes.Attributes); console.log("更新后的用户数据:", updatedUser); return updatedUser; } // 无更新需求则直接返回查询到的用户数据 return userData; } catch (err) { console.error("操作失败:", err); throw err; } };
测试方法
修改你的event.json传入测试参数即可:
{ "userId": "你要操作的用户ID", "updateCoins": 10 }
本地可通过amplify mock function <你的函数名>测试,也可以直接在Lambda控制台上传代码后直接测试。
注意事项
- 表名一定要替换为Amplify实际生成的完整表名,不要直接填写
User - GraphQL模型的
@auth规则仅针对AppSync GraphQL请求校验,Lambda直接操作DynamoDB不受该规则限制,需自行做好操作权限控制 - 如果你的Lambda不是DynamoDB触发器类型,可以删除开头处理
event.Records的逻辑段
内容的提问来源于stack exchange,提问作者Mr. Curious
相关产品推荐
相关产品推荐

