쿼리 함수
쿼리 함수필드 응답 제거

필드 응답 제거

Included in the “Power Extensions” bundle

GraphQL 스키마에 @remove 디렉티브를 추가하여, 필드의 출력을 응답에서 제거합니다.

설명

GraphQL 사양에서는 GraphQL 응답이 쿼리의 형태와 정확히 일치해야 한다고 명시하고 있습니다. 그러나 특정 상황에서는 다음과 같은 이유로 필드의 응답을 반환하지 않는 것이 바람직할 수 있습니다.

  • 이미 그 값을 알고 있어, 다시 전송하지 않음으로써 성능을 향상시킬 수 있습니다
  • 로그인 자격 증명과 같은 민감한 정보가 포함되어 있습니다
  • 빈 필드를 null 값과 구별할 수 있습니다

필드에 @remove를 추가하면, 해당 필드는 응답에 출력되지 않습니다.

아래 쿼리(PHP Functions via SchemaHTTP Client 확장을 사용)에서는 사이트 도메인과 REST API 엔드포인트를 연결하여 HTTP 요청을 전송할 URL을 생성합니다. 이러한 "구성 요소"의 값은 응답에 포함할 필요가 없으므로, @remove로 제거할 수 있습니다.

query {
  siteURL: optionValue(name: "siteurl")
    @remove
 
  requestURL: _sprintf(
    string: "%s/wp-json/wp/v2/comments/11/?_fields=id,content,date",
    values: [$__siteURL]
  )
    @remove
 
  _sendJSONObjectItemHTTPRequest(
    input: {
      url: $__requestURL
    }
  )
}

...결과(siteURLrequestURL 필드가 응답에 포함되지 않은 것을 확인하세요):

{
  "data": {
    "_sendJSONObjectItemHTTPRequest": {
      "id": 11,
      "date": "2020-12-12T04:07:36",
      "content": {
        "rendered": "<p>Btw, I really like this stuff<\/p>\n"
      }
    }
  }
}

또한 @remove 디렉티브에 조건을 지정하여, 조건이 충족될 때만 값을 제거하도록 설정할 수도 있습니다. condition 인수에는 3가지 값을 지정할 수 있습니다.

  • ALWAYS(기본값): 항상 제거합니다
  • IS_NULL: 값이 null일 때 제거합니다
  • IS_EMPTY: 값이 비어 있을 때 제거합니다

예를 들어, 아래 쿼리에서는 게시물에 대표 이미지가 없을 경우 featuredImage 필드의 값이 null이 됩니다. @remove(condition: IS_NULL)을 추가하면 이 값은 응답에 추가되지 않습니다.

query {
  posts {
    title
    featuredImage @remove(condition: IS_NULL) {
      src
    }
  }
}

...결과:

{
  "data": {
    "posts": [
      {
        "title": "Hello world!"
      },
      {
        "title": "Nested mutations are a must have",
        "featuredImage": {
          "src": "https:\/\/gato-graphql.lndo.site\/wp-content\/uploads\/2022\/05\/graphql-voyager-public.jpg"
        }
      },
      {
        "title": "Customize the schema for each client"
      }
    ]
  }
}

사용 예시

외부 API에서 불필요한 데이터 제거하기

외부 REST API 엔드포인트에서 특정 데이터를 가져오고 나머지 데이터는 필요하지 않은 경우를 가정해 봅시다. @remove를 사용하여 응답 페이로드를 줄이면 성능을 향상시킬 수 있습니다.

  • _sendJSONObjectItemHTTPRequest 필드(HTTP Client 확장)를 사용하여 REST API에 연결합니다
  • Field to InputPHP Function via Schema_objectProperty 필드를 사용하여 필요한 정보를 추출합니다
  • @remove로 REST 엔드포인트에서 가져온 원본 데이터를 제거합니다

다음 쿼리가 이 모든 것을 하나로 묶습니다.

{
  postData: _sendJSONObjectItemHTTPRequest(input: {
    url: "https://newapi.getpop.org/wp-json/wp/v2/posts/1"
  }) @remove
  renderedTitle: _objectProperty(
    object: $__postData,
    by: {
      path: "title.rendered"
    }
  )
}

이 쿼리의 응답에서 postData 필드가 제거되었습니다.

{
  "data": {
    "renderedTitle": "Hello world!"
  }
}

사용자 자격 증명 출력 방지하기

이 예시에서는 GitHub API에 연결하여 비공개 리포지토리에서 사용 가능한 아티팩트를 가져오고, 사용자의 자격 증명이 응답에 출력되지 않도록 합니다.

query RetrieveGitHubActionArtifacts(
  $repoOwner: String!
  $repoProject: String!
) {
  githubAccessToken: _env(name: "GITHUB_ACCESS_TOKEN")
    @remove
 
  # Create the authorization header to send to GitHub
  authorizationHeader: _sprintf(
    string: "Bearer %s"
    # "Field to Input" feature to access value from the field above
    values: [$__githubAccessToken]
  )
    @remove
 
  # Create the authorization header to send to GitHub
  githubRequestHeaders: _echo(
    value: [
      { name: "Accept", value: "application/vnd.github+json" }
      { name: "Authorization", value: $__authorizationHeader }
    ]
  )
    @remove
 
  githubAPIEndpoint: _sprintf(
    string: "https://api.github.com/repos/%s/%s/actions/artifacts"
    values: [$repoOwner, $repoProject]
  )
 
  # Use the field from "Send HTTP Request Fields" to connect to GitHub
  gitHubArtifactData: _sendJSONObjectItemHTTPRequest(
    input: {
      url: $__githubAPIEndpoint
      options: { headers: $__githubRequestHeaders }
    }
  )
}

GraphQL 사양

이 기능은 현재 GraphQL 사양의 일부가 아니지만, 요청이 제출되어 있습니다.