3
votes

Background: I'm using Amplify to create a type Item @model GraphQL datastore with an @auth allow owner which adds the owner as an CognitoID to the Item.

Question: This item is readable for guests and I would like to show the owner (or other related metadata such as a username/email) for this item.

e.g. Cognito.GetUserAttributes(2b10fb7e-4472-43c9-9bb9-54219b5027a3)

Is somthing like this possible? How is this supposed to be designed for this use case? Do I have to add a lambda that adds the user meta data to the item when it is created?

I would like this solution to be scalable.


The schema:

type Item
@model
@auth(rules: [
    { allow: owner},
    { allow: groups, groups: ["Admin"] },
    { allow: private, operations: [read] },
    { allow: public, operations: [read] }
])
{
    id: ID!
    title: String!
    description: String
}

From DynamoDB:

{
  "__typename": "Item",
  "_lastChangedAt": 1593707126605,
  "_version": 1,
  "createdAt": "2020-07-02T16:25:26.582Z",
  "description": "Description",
  "id": "0592fcd8-408e-406e-84bf-9f63eb43e147",
  "owner": "2b10fb7e-4472-43c9-9bb9-54219b5027a3",
  "title": "Item",
  "updatedAt": "2020-07-02T16:25:26.582Z"
}
1

1 Answers

1
votes

You can use a function resolver on a cognitoAttributes field. The lambda function can call admin-get-user in Cognito and return the attributes. The lambda function will receive the dynamo Item in the event.source property so you will have access to the owner id to make the call to Cognito.

type Item
@model
@auth(rules: [
    { allow: owner},
    { allow: groups, groups: ["Admin"] },
    { allow: private, operations: [read] },
    { allow: public, operations: [read] }
])
{
    id: ID!
    title: String!
    cognitoAttributes: [String]! @function('cognitoGetUserAttributes-${env})
    description: String
}