Search code examples
graphqlaws-appsync

In an AppSync @auth rule, how do I set an ownerField to a property in an array?


Imagine I have the following AppSync GraphQL schema with a User type, and a Post type with an editors field set to an array of Users:

type User
  @model 
  @auth(rules: [
    { allow: owner }
  ])
{
  id: ID!
  owner: String!
  username: String!
}

type Post
  @model
  @auth(rules: [
    { allow: owner },
    # Can I do this?
    # { allow: owner, ownerField: "editors.owner", operations: [update] }
  ])
{
  id: ID!
  owner: String!
  title: String!
  content: String
  editors: [User]
}

How do I create an @auth rule to give update permissions to the Users in the editors array?


Solution

  • If you're using the amazon Cognito user pool you should set the editor type inside Post to be an array of String and set the values to the Cognito ids of the users that you want to have access. This is explained in the amplify cli documentation.

    To have the editors to be of type User I suggest you to create another paramether named differently (for example editorUsers) and connect it to the User model as described here

    Your schema should look like this:

    type User
    @model
    @key(name: "byUser", fields: ["username"]) 
    @auth(rules: [
     { allow: owner }
    ])
    {
      id: ID!
      owner: String!
      username: String!
    }
    
    type Post
    @model
    @auth(rules: [
      { allow: owner },
      { allow: owner, ownerField: "editors", operations: [update] }
    ])
    {
      id: ID!
      owner: String!
      title: String!
      content: String
      editors: [String]
      editorsUsers: [User] @connection(keyName: "byUser", fields: ["id"])
    }