使用 aws-amplify 更新 GraphQL 对象时出现授权错误

Authorization error when updating a GraphQL object using aws-amplify

我在使用 aws amplify 生成 graphql 时遇到问题API

我的模型主要有两个对象(用户和消息):

用户对象:

type User
  @model(subscriptions: null)
  @auth(rules: [{ allow: owner, ownerField: "id" }]) {
  id: ID!
  email: String!
  username: String!
  avatar: S3Object
  name: String
  conversations: [Conversation] @manyToMany(relationName: "UserConversations")
  messages: [Message!]! @hasMany(indexName: "byAuthor", fields: ["id"])
  createdAt: String
  updatedAt: String
}

消息对象:

type Message
  @model(subscriptions: null)
  @auth(
    rules: [
      {
        allow: owner
        ownerField: "authorId"
        operations: [create, update, delete]
      }
    ]
  ) {
  id: ID!
  author: User @belongsTo(fields: ["authorId"])
  authorId: ID! @index(name: "byAuthor", sortKeyFields: ["content"])
  content: String!
  conversation: Conversation! @belongsTo(fields: ["messageConversationId"])
  messageConversationId: ID!
    @index(name: "byConversation", sortKeyFields: ["createdAt"])
  createdAt: String
  updatedAt: String
}

两者之间存在 hasMany/belongsTo 关系,并且两者都有 auth 规则。

在我登录 API 并尝试通过 JS API 创建用户对象后,出现以下错误

'Not Authorized to access messages on type ModelMessageConnection'

        await AuthAPI.graphql(
          graphqlOperation(createUser, {
            input: {
              id,
              username,
              email,
              name,
            },
          })
        );

这实际上是由于 message 规则缺少 read 操作。将对象模型更改为下面的代码修复它

type Message
  @model(subscriptions: null)
  @auth(
    rules: [
      {
        allow: owner
        ownerField: "authorId"
        operations: [create, update, delete, read]
      }
    ]
  ) {
  id: ID!
  author: User @belongsTo(fields: ["authorId"])
  authorId: ID! @index(name: "byAuthor", sortKeyFields: ["content"])
  content: String!
  conversation: Conversation! @belongsTo(fields: ["messageConversationId"])
  messageConversationId: ID!
    @index(name: "byConversation", sortKeyFields: ["createdAt"])
  createdAt: String
  updatedAt: String
}