AWS AppSync에서 hasMany 항목 가져오기

User 모델에 posts: [Post]를 추가한다.

type User {
  id: ID!
  name: String
  birthday: AWSDate
  posts: [Post]
}

Scheme – Resolver – User – posts:[Post] 의 연결(Attach)를 누르면 resolver 설정하는 화면으로 간다. 상단의 테이블 선택은 Post 테이블을 선택하고, request에는 템플릿에서 Simple query를 선택한 뒤에 이렇게 넣어준다. 그런 다음 DynamoDB의 Post 테이블에 가서 userId-index 라는 인덱스를 만들어준다.

{
  "version": "2017-02-28",
  "operation": "Query",
  "index": "userId-index",
  "query": {
    "expression": "userId = :userId",
    "expressionValues": {
      ":userId": {
        "S": $util.toJson($context.source.id)
      }
    }
  }
}

response는 이렇게 넣어준다.

$util.toJson($ctx.result.items)

그 후에 listUsers 쿼리에 이렇게 넣어주면 사용자 정보를 불러올 때 작성한 글도 같이 불러올 수 있다.

query listUsers {
  listUsers {
    items {
      id
      name
      birthday
      posts {
        id
        title
      }
    }
  }
}
{
  "data": {
    "listUsers": {
      "items": [
        {
          "id": "a98f6a96-73c5-407e-b7b3-7b5b95da1b8e",
          "name": "Hello, world!",
          "birthday": "1970-01-01Z",
          "posts": [
            {
              "id": "11",
              "title": "제목"
            }
          ]
        }
      ]
    }
  }
}