AWS amplify Getting the owner data not only the Id

Viewed 635

Is something like this possible? How is this supposed to be designed for this use case? Do I have to add a lambda function that adds the user (owner) to the post when it is created?

Can anyone help me to accomplish that .. Thanks!

This is Post schema:

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"])
}

And when I fetch the post, this is what I got:

{
    "id": "xxxxxxx",
    "content": "xxxxx!",
    "upVotes": 0,
    "downVotes": 0,
    "image": null,
    "clubId": "xxxxxx",
    "comments": {
        "nextToken": null
    },
    "createdAt": "2021-12-05T10:46:59.797Z",
    "updatedAt": "2021-12-05T10:46:59.797Z",
    "owner": "moneebalalfi@gmail.com"
}

I want something like this:

{
    "id": "xxxxx",
    "content": "xxxxxxx",
    "upVotes": 0,
    "downVotes": 0,
    "image": null,
    "clubId": "xxxxxxxx",
    "comments": {
        "nextToken": null
    },
    "createdAt": "2021-12-05T10:46:59.797Z",
    "updatedAt": "2021-12-05T10:46:59.797Z",
    "owner": {
       name: "xxxxx",
       email: "xxxx@gmail.com",
       image: "xxxxxx",
       // and so on ...
    }

}
1 Answers

owner field is only used for checking if the requested user is the owner of the data.

Owner authorization specifies whether a user can access or operate against an object. To do so, each object will get an ownerField field (by default owner will be added to the object if not specified) that stores ownership information and is verified in various ways during resolver execution.

from Amplify Docs

To be able to make a connection with the user you need to create another GraphQL Type.

type User
  @model 
  @auth(
    rules: [
      { allow: owner, operations: [create, update, delete, read] }
      { allow: private, operations: [read] }
    ]
  ) {
  id: ID!
  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!
  owner: ID
  user: User @connection(fields: ["owner"])
  comments: [Comment] @connection(keyName: "byPost", fields: ["id"])
}

You might need to configure amplify codegen to increase the max-depth, if it's not showing.

$ amplify configure codegen 
$ amplify codegen
Related