AWS Amplify获取Post完整owner数据而非仅ID的实现方案咨询
需求完全可以实现,不需要在创建Post时新增Lambda写入用户信息,主流有两种实现方案:
方案1:Schema关联方案(推荐,无需额外Lambda)
这是Amplify的官方最佳实践,仅需要修改GraphQL Schema,通过表关联自动返回结构化的用户信息:
- 新增
User模型存储用户公开信息,用户注册时通过Cognito的Post Confirmation触发器自动同步用户信息到User表即可 - 显式声明Post的
owner字段,关联到User表,保留原有@auth规则即可
修改后的Schema示例:
# 用户信息表 type User @model @auth(rules: [ # 仅用户本人可修改自己的信息,所有登录用户可读取公开信息 { allow: owner, operations: [update, read] }, { allow: private, operations: [read] } ]) { # 该字段值和Post的owner字段值保持一致,可存用户邮箱或Cognito用户ID id: ID! name: String email: String image: String } type Post @model @key(name: "byClub", fields: ["clubId"]) @auth( rules: [ { allow: owner, operations: [create, update, delete, read] } { allow: private, operations: [read] } ] ) { id: ID! content: String! upVotes: Int! downVotes: Int! image: String clubId: ID! comments: [Comment] @connection(keyName: "byPost", fields: ["id"]) # 关联用户表,Amplify Transformer v2可将@connection替换为@hasOne owner: User @connection(fields: ["owner"]) }
查询时只要在请求语句中嵌套请求owner的字段即可,示例查询语句:
query GetPost($postId: ID!) { getPost(id: $postId) { id content upVotes downVotes image clubId createdAt updatedAt # 嵌套查询用户信息 owner { name email image } comments { nextToken } } }
方案2:自定义Lambda解析器方案
如果你不想额外维护User表,所有用户信息都存储在Cognito用户池中,可以给Post的owner字段配置自定义Lambda解析器:
- 不需要修改Post表的现有存储结构
- 查询Post时,Lambda会自动根据owner字段的邮箱值,调用Cognito接口拉取对应用户的信息,组装成结构化对象返回
选型建议
- 优先选择方案1:关联查询性能更高,符合GraphQL的设计规范,后续扩展用户自定义字段更方便
- 仅当用户信息完全不需要额外存储自定义字段时,再选择方案2
内容的提问来源于stack exchange,提问作者Harvey Specter
相关产品推荐
相关产品推荐

