【问题标题】:Using user info in AWS Amplify GraphQL schema在 AWS Amplify GraphQL 架构中使用用户信息
【发布时间】:2022-04-19 11:12:11
【问题描述】:

我正在尝试为我的应用程序构建一个数据库,其中一个关键部分是用户与数据库中的各种模型的关联。我也在使用 Amplify 的身份验证来管理用户。以下是他们博客文章示例的略微修改版本。

type Blog @model {
  id: ID!
  name: String!
  posts: [Post] @connection(name: "BlogPosts")
}

type Post @model {
  id: ID!
  title: String!
  blog: Blog @connection(name: "BlogPosts")
  comments: [Comment] @connection(name: "PostComments")
  user: ##userid##???
  likes: 0
}

type Comment @model {
  id: ID!
  content: String
  post: Post @connection(name: "PostComments")
  user: ##userid##???
}

这是我看到的一些问题。我可能想显示用户名和个人资料图片。我知道我可以为用户存储一个可选属性,例如图片 url,但是我可以访问其他用户的属性,因为他们不是当前经过身份验证的用户吗?另外,我将如何跟踪特定用户喜欢的帖子?我可以在 Post 模型上添加一个 likeBy 用户列表,但如果我想获得一个用户的所有喜欢的帖子,那将根本无法很好地扩展。然后在最低级别是存储创建帖子的用户的问题。没有用户模型可以与之关联以获取所有特定用户的帖子。解决方案是只拥有一个用户模型并通过身份验证对其进行管理吗?

【问题讨论】:

    标签: javascript reactjs amazon-web-services aws-amplify aws-amplify-cli


    【解决方案1】:

    让我试着帮助你。

    首先,我建议您将您的模型与某种身份验证相关联,以便他们知道哪个用户创建了什么。 Cognito is pretty simple to start with.

    之后你的模型看起来像(我调整了你的模型以反映最新版本的放大,没有测试它,但你可以read more about it here):

    type Blog @model 
      @auth(rules: [{ allow: owner }])
    {
      id: ID!
      name: String!
      posts: [Post] @hasMany(indexName: "byBlog", fields: ["id"])
    }
    
    type Post @model 
      @auth(rules: [{ allow: owner }])
    {
      id: ID!
      blogID: ID! @index(name: "byBlog")
      post: Post @belongsTo(fields: ["blogID"])
      title: String!
      likes: 0
      comments: [Comment] @hasMany
    }
    
    type Comment @model 
      @auth(rules: [{ allow: owner }])
    {
      id: ID!
      content: String
    }
    

    之后,您可以创建一个 lambda 函数,该函数将获取用户信息(基于 owner 属性,除非您指定它,否则该属性是隐藏的)您可以向模型添加一个新属性,如下所示:

    createdBy: Owner @function(name: "getOwnerDetails-${env}")
    

    所以你现在的模型看起来像:

    type Owner {
        email: String
        name: String
        photo: String
    }
    
    type Comment @model 
      @auth(rules: [{ allow: owner }])
    {
      id: ID!
      content: String
      createdBy: Owner @function(name: "getOwnerDetails-${env}")
    }
    

    我不能告诉你 lambda 函数的细节,因为我的函数中有一些额外的东西,而且它非常适合我的情况,但我相信你可以解决它,只要确保你可以访问你的Cognito 及其属性,您需要做的就是返回它:)

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 2020-04-05
      • 2020-01-05
      • 2019-04-21
      • 2020-12-22
      • 2020-08-19
      • 2019-06-02
      • 2020-03-27
      • 2020-03-02
      相关资源
      最近更新 更多