GraphQL API와의 상호작용
GraphQL API와의 상호작용응답에서 필드가 출력되는 경로 변경하기

응답에서 필드가 출력되는 경로 변경하기

이 질문은 Reddit에 게시된 것입니다:

I have:

allMdx {
  edges {
    node {
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
      }
    }
  }
}

I need frontmatter.date to be publishedAt:

allMdx {
  edges {
    node {
      publishedAt: frontmatter{date(formatString: "MMMM DD, YYYY")}
    }
  }
}

Problem is, when I do this, I end up with:

{
  "publishedAt": {
    "date": "February 06, 2021"
  }
}

Instead of (which is what I need):

{
  "publishedAt": "February 06, 2021"
}

Is it even possible to alias nested fields like this?

즉, GraphQL 서버에 응답의 형태를 평탄화하도록 지시하는 것이 가능한지, 그리고 가능하다면 그 방법은 무엇인지에 관한 질문입니다.

다음 확장 기능을 활용한 Gato GraphQL의 해결책을 소개합니다:

@export를 사용하면 첫 번째 쿼리 작업에서 일부 결과를 변수로 내보낸 다음, 해당 변수를 읽어 응답의 원하는 위치에 출력하는 두 번째 쿼리 작업을 선언할 수 있습니다:

query ExportDate
{
  allMdx {
    edges {
      node {
        frontmatter {
          date(formatString: "MMMM DD, YYYY")
            @export(as: "date")
        }
      }
    }
  }
}
 
query PrintRelocatedDate($date: String)
  @depends(on: "ExportDate")
{
  allMdx {
    edges {
      node {
        publishedAt: _echo(value: $date)
      }
    }
  }
}

...그리고 쿼리를 실행(?operationName=PrintRelocatedDate를 전달)하면 다음과 같은 응답이 반환됩니다:

{
  "data": {
    "allMdx": {
      "edges": [
        {
          "frontmatter": {
            "publishedAt": "February 06, 2021"
          },
          "publishedAt": "February 06, 2021"
        }
      ]
    }
  }
}