如何使用AWS CDK为AppSync创建更新DynamoDB项的Resolver
实现DynamoDB更新操作的AppSync Resolver逻辑如下
首先先确认你的GraphQL Schema中已定义对应的更新Mutation字段,参考定义:
# 用于更新的输入类型,可根据你的业务字段调整 input UpdateConfigSettingsInput { id: ID! # 其余可更新字段和你原有ConfigSettings类型的字段保持一致即可 configName: String configValue: String enableStatus: Boolean } type Mutation { # 你原有新增的mutation字段 createConfigSettings(configSettings: CreateConfigSettingsInput!): ConfigSettings # 新增的更新mutation字段 updateConfigSettings(id: ID!, configSettings: UpdateConfigSettingsInput!): ConfigSettings }
之后在CDK代码中添加更新Resolver的逻辑即可:
const configSettingsDS = api.addDynamoDbDataSource('configSettingsDynamoTable', configurationSettingsTable); // 原有新增逻辑保留 configSettingsDS.createResolver({ typeName:'Mutation', fieldName: 'createConfigSettings', requestMappingTemplate: appsync.MappingTemplate.dynamoDbPutItem( appsync.PrimaryKey.partition('id').auto(), appsync.Values.projecting('configSettings')), responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultItem(), }); // 新增更新逻辑 configSettingsDS.createResolver({ typeName: 'Mutation', fieldName: 'updateConfigSettings', requestMappingTemplate: appsync.MappingTemplate.dynamoDbUpdateItem( // 指定需要更新的条目主键,从请求参数中获取传入的id appsync.PrimaryKey.partition('id').is('$ctx.args.id'), // 投射传入的configSettings参数作为需要更新的字段值 appsync.Values.projecting('configSettings'), // 可选配置:仅当指定id的条目已存在时才执行更新,避免误插入新条目 appsync.Condition.attributeExists('id') ), responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultItem(), });
核心逻辑说明
- 替换新增用的
dynamoDbPutItem为dynamoDbUpdateItem方法实现更新操作 - 主键不能使用
auto()自动生成,必须通过.is()指定待更新条目的主键值,从请求参数中取值 - 第三个条件参数为可选项,不需要校验条目存在可以直接删除
- 返回映射模板和新增逻辑保持一致即可,会直接返回更新完成后的最新数据
内容的提问来源于stack exchange,提问作者Yasas Nanayakkara
相关产品推荐
相关产品推荐

