Query Functions
Query Functionsフィールド上のフィールド

フィールド上のフィールド

Included in the “Power Extensions” bundle

@applyField ディレクティブは、解決されたフィールドの値に対して特定のフィールドを実行します。

説明

あるフィールドに適用すると、@applyField ディレクティブは別のフィールド(同じタイプで利用可能で、同じオブジェクトに適用されるもの)を実行し、その結果の値を別のディレクティブに渡すか、フィールドの値を上書きすることができます。

これにより、PHP Functions via Schema 拡張機能が提供する機能を適用してフィールドの値をさまざまな方法で操作し、新しい結果をレスポンスに格納することができます。

以下のクエリでは、オブジェクトの Post.title フィールドの値は "Hello world!" です。@applyField を追加して _strUpperCase フィールドを実行し(その前に @passOnwards を付けてフィールドの値を動的な $input としてエクスポートします):

{
  post(by: { id: 1 }) {
    title
      @passOnwards(as: "input")
      @applyField(
        name: "_strUpperCase"
        arguments: {
          text: $input
        },
        setResultInResponse: true
      )
  }
}

...フィールドの値が大文字に変換され、次の結果が得られます:

{
  "data": {
    "post": {
      "title": "HELLO WORLD!"
    }
  }
}

複数の @applyFunction を連結し、一方のレスポンスを他方への入力として使用することで、同じフィールドの値に対して複数の操作を実行できます。

以下のクエリでは、2つの @applyFunction 操作が適用されています:

  1. 大文字に変換し、その値を $ucTitle として次に渡す
  2. " ""-" に置換してフィールドの値を上書きする
{
  post(by: { id: 1 }) {
    title
      @passOnwards(as: "input")
      @applyField(
        name: "_strUpperCase"
        arguments: {
          text: $input
        },
        passOnwardsAs: "ucTitle"
      )
      @applyField(
        name: "_strReplace"
        arguments: {
          search: " ",
          replaceWith: "-",
          in: $ucTitle
        },
        setResultInResponse: true
      )
  }
}

...次の結果が得られます:

{
  "data": {
    "post": {
      "title": "HELLO-WORLD!"
    }
  }
}

さらなる例

フィールドが提供する値の逆の値を取得する:

{
  posts {
    id
    notHasComments: hasComments
      @passOnwards(as: "hasComments")
      @applyField(
        name: "_not",
        arguments: {
          value: $hasComments
        },
        setResultInResponse: true
      )
  }
}

Data Iteration Meta Directives 拡張機能と合わせて、配列内のすべてのアイテムを操作し、それぞれを最大20文字に短縮する:

{
  posts {
    categoryNames
      @underEachArrayItem(passValueOnwardsAs: "categoryName")
        @applyField(
          name: "_strSubstr"
          arguments: {
            string: $categoryName,
            offset: 0,
            length: 20
          },
          setResultInResponse: true
        )
  }
}

Data Iteration Meta Directives 拡張機能と合わせて、配列の最初のアイテムを大文字に変換する:

{
  posts {
    categoryNames
      @underArrayItem(passOnwardsAs: "value", index: 0)
        @applyField(
          name: "_strUpperCase"
          arguments: {
            text: $value
          },
          setResultInResponse: true
        )
  }
}