Query Functions
Query Functionsフィールド値の反復と操作

フィールド値の反復と操作

Included in the “Power Extensions” bundle

GraphQLスキーマにメタディレクティブを追加し、arrayおよびobjectフィールドの値要素を反復・操作します:

  1. @underArrayItem
  2. @underJSONObjectProperty
  3. @underEachArrayItem
  4. @underEachJSONObjectProperty
  5. @objectClone

@underArrayItem

@underArrayItem は、ネストされたディレクティブをarray内の特定の要素に適用します。

以下のクエリでは、カテゴリー名のarrayのうち最初の要素だけが大文字に変換されます:

query {
  posts {
    categoryNames
      @underArrayItem(index: 0)
        @strUpperCase
  }
}

...の結果:

{
  "data": {
    "posts": {
      "categoryNames": [
        "NEWS",
        "sports"
      ]
    }
  }
}

@underJSONObjectProperty

@underJSONObjectProperty は、ネストされたディレクティブがクエリ対象のJSONオブジェクトのエントリを受け取れるようにします。

このディレクティブは、外部APIをクエリした後に目的のデータを抽出・操作するのに特に有用です。外部APIはほぼ確実にジェネリックな JSONObject 型を持っており(HTTP Client エクステンションの関数フィールド _sendJSONObjectItemHTTPRequest を使用する場合など)、その際に役立ちます。

以下のクエリでは、WP REST APIから取得したJSONオブジェクトを使用し、@underJSONObjectProperty でレスポンスの type プロパティを操作して大文字に変換します:

query {
  postData: _sendJSONObjectItemHTTPRequest(input: {
    url: "https://newapi.getpop.org/wp-json/wp/v2/posts/1/?_fields=id,type,title,date"
  })
    @underJSONObjectProperty(by: { key: "type" })
      @strUpperCase
}

これにより以下が生成されます:

{
  "data": {
    "postData": {
      "id": 1,
      "date": "2019-08-02T07:53:57",
      "type": "POST",
      "title": {
        "rendered": "Hello world!"
      }
    }
  }
}

JSONオブジェクトの第1レベルにあるプロパティを指定する "key" を受け取ることに加え、このディレクティブはオブジェクトの内部構造をナビゲートするための "path" も受け取ることができます。レベル間の区切り文字には . を使用します。

以下のクエリでは、投稿に対するWP REST APIエンドポイントがプロパティ "title.rendered" を提供します。その実際のサブ要素にナビゲートし、タイトルケースに変換できます:

query {
  postData: _sendJSONObjectItemHTTPRequest(input: {
    url: "https://newapi.getpop.org/wp-json/wp/v2/posts/1/?_fields=id,type,title,date"
  })
    @underJSONObjectProperty(by: { path: "title.rendered" })
      @strTitleCase
}

これにより以下が生成されます:

{
  "data": {
    "postData": {
      "id": 1,
      "date": "2019-08-02T07:53:57",
      "type": "post",
      "title": {
        "rendered": "HELLO WORLD!"
      }
    }
  }
}

@underEachArrayItem

@underEachArrayItem は、クエリ対象のエンティティのあるフィールドのarray要素を反復処理し、それぞれに対してネストされたディレクティブを実行します。

たとえば、フィールド Post.categoryNames[String] 型です。@underEachArrayItem を使用することで、カテゴリー名を反復し、@strTranslate ディレクティブを適用できます。

このクエリでは、投稿のカテゴリーが英語からフランス語に翻訳されます:

query {
  posts {
    id
    title
    categoryNames
      @underEachArrayItem
        @strTranslate(
          from: "en",
          to: "fr"
        )
  }
}

...の結果:

{
  "data": {
    "posts": [
      {
        "id": 662,
        "title": "Explaining the privacy policy",
        "categoryNames": [
          "Non classé"
        ]
      },
      {
        "id": 28,
        "title": "HTTP caching improves performance",
        "categoryNames": [
          "Avancé"
        ]
      },
      {
        "id": 25,
        "title": "Public or Private API mode, for extra security",
        "categoryNames": [
          "Ressource",
          "Blog",
          "Avancé"
        ]
      }
    ]
  }
}

@underEachArrayItem は、ディレクティブ引数 passIndexOnwardsAspassValueOnwardsAs を通じて、反復中の要素のインデックスと値の両方をネストされたディレクティブへ動的変数として渡すことができます。

このクエリは動的変数 $index$value の使用例を示しています:

{
  _echo(value: ["first", "second", "third"])
    @underEachArrayItem(
      passIndexOnwardsAs: "index"
      passValueOnwardsAs: "value"
    )
      @applyField(
        name: "_echo"
        arguments: {
          value: {
            index: $index,
            value: $value
          }
        },
        setResultInResponse: true
      )
}

結果は以下のとおりです:

{
  "data": {
    "_echo": [
      {
        "index": 0,
        "value": "first"
      },
      {
        "index": 1,
        "value": "second"
      },
      {
        "index": 2,
        "value": "third"
      }
    ]
  }
}

@underEachArrayItem はまた、パラメーター filter->by によって反復するarrayの位置を制限することもできます。このパラメーターは include または exclude のいずれかのエントリを受け取ります。

このクエリ:

{
  including: _echo([
    "first",
    "second",
    "third"
  ])
    @underEachArrayItem(
      filter: {
        by: {
          include: [0, 2]
        }
      }
    )
      @strUpperCase
 
  excluding: _echo([
    "first",
    "second",
    "third"
  ])
    @underEachArrayItem(
      filter: {
        by: {
          exclude: [0, 2]
        }
      }
    )
      @strUpperCase
}

...の結果:

{
  "data": {
    "including": [
      "FIRST",
      "second",
      "THIRD"
    ],
    "excluding": [
      "first",
      "SECOND",
      "third"
    ]
  }
}

@underEachJSONObjectProperty

@underEachJSONObjectProperty@underEachArrayItem に似ていますが、JSONObject 要素を対象として動作します。

このクエリでは、JSONオブジェクトのすべてのエントリを反復し、null のエントリを空文字列に置き換えます:

{
  _echo(
    value: {
      first: "hello",
      second: "world",
      third: null
    }
  )
    @underEachJSONObjectProperty
      @default(value: "")
}

...の結果:

{
  "data": {
    "_echo": {
      "first": "hello",
      "second": "world",
      "third": ""
    }
  }
}

@underEachJSONObjectProperty は、ディレクティブ引数 passKeyOnwardsAspassValueOnwardsAs を通じて、反復中のキーと値をネストされたディレクティブへ動的変数として渡すことができます。

このクエリは動的変数 $key$value の使用例を示しています:

{
  _echo(value: {
    uno: "first",
    dos: "second",
    tres: "third"
  })
    @underEachJSONObjectProperty(
      passKeyOnwardsAs: "key"
      passValueOnwardsAs: "value"
    )
      @applyField(
        name: "_echo"
        arguments: {
          value: {
            key: $key,
            value: $value
          }
        },
        setResultInResponse: true
      )
}

結果は以下のとおりです:

{
  "data": {
    "_echo": {
      "uno": {
        "key": "uno",
        "value": "first"
      },
      "dos": {
        "key": "dos",
        "value": "second"
      },
      "tres": {
        "key": "tres",
        "value": "third"
      }
    }
  }
}

@underEachJSONObjectProperty はまた、パラメーター filter->by によって反復するJSONオブジェクトのキーを制限することもできます。このパラメーターは includeKeys または excludeKeys のいずれかのエントリを受け取ります。

このクエリ:

{
  includingKeys: _echo(value: {
    uno: "first",
    dos: "second",
    tres: "third"
  })
    @underEachJSONObjectProperty(
      filter: {
        by: {
          includeKeys: ["uno", "tres"]
        }
      }
    )
      @strUpperCase
 
  excludingKeys: _echo(value: {
    uno: "first",
    dos: "second",
    tres: "third"
  })
    @underEachJSONObjectProperty(
      filter: {
        by: {
          excludeKeys: ["uno", "tres"]
        }
      }
    )
      @strUpperCase
}

...の結果:

{
  "data": {
    "includingKeys": {
      "uno": "FIRST",
      "dos": "second",
      "tres": "THIRD"
    },
    "excludingKeys": {
      "uno": "first",
      "dos": "SECOND",
      "tres": "third"
    }
  }
}

@objectClone

JSONオブジェクトは、フィールドリゾルバーにおいてオブジェクトをコピー・複製するのではなく、参照によりアクセスされる場合があります。その場合、JSONオブジェクトが変更されると、その変更はそのJSONオブジェクトを取得するすべてのフィールドに反映されます。

これはフィールド Block.attributes の場合に該当します:

{
  posts {
    blocks(filterBy: { include: "core/heading" } ) {
      attributes
    }
  }
}

...の結果:

{
  "data": {
    "posts": [
      {
        "blocks": [
          {
            "attributes": {
              "content": "Image Block (Full width)",
              "level": 2
            }
          },
          {
            "attributes": {
              "content": "Gallery Block",
              "level": 2
            }
          }
        ]
      }
    ]
  }
}

以下のクエリでは、originalAttributes が単に属性を取得するのに対し、transformedAttributescontent プロパティをフランス語に翻訳します:

{
  posts {
    blocks(filterBy: { include: "core/heading" } ) {
      originalAttributes: attributes
      transformedAttributes: attributes
        @underJSONObjectProperty(by: { key: "content" })
          @strTranslate(to: "fr")
    }
  }
}

しかし、クエリ対象の Block エンティティが originalAttributestransformedAttributes の両方で同じJSONオブジェクトを参照しているため、後者のフィールドが行った変換は前者のフィールドにも影響します(これはクエリ内での出現順序に関係なく発生します)。

その結果、両方のフィールドがフランス語に翻訳されます:

{
  "data": {
    "posts": [
      {
        "blocks": [
          {
            "originalAttributes": {
              "content": "Bloc d'image (pleine largeur)",
              "level": 2
            },
            "transformedAttributes": {
              "content": "Bloc d'image (pleine largeur)",
              "level": 2
            }
          },
          {
            "originalAttributes": {
              "content": "Bloc Galerie",
              "level": 2
            },
            "transformedAttributes": {
              "content": "Bloc Galerie",
              "level": 2
            }
          }
        ]
      }
    ]
  }
}

transformedAttributes フィールドにディレクティブ @objectClone を追加することで、変更がクローンされたJSONオブジェクトに対して行われるようになり、この問題を回避できます:

{
  posts {
    blocks(filterBy: { include: "core/heading" } ) {
      originalAttributes: attributes
      transformedAttributes: attributes
        @objectClone
        @underJSONObjectProperty(by: { key: "content" })
          @strTranslate(to: "fr")
    }
  }
}

...の結果:

{
  "data": {
    "posts": [
      {
        "blocks": [
          {
            "originalAttributes": {
              "content": "Image Block (Full width)",
              "level": 2
            },
            "transformedAttributes": {
              "content": "Bloc d'image (pleine largeur)",
              "level": 2
            }
          },
          {
            "originalAttributes": {
              "content": "Gallery Block",
              "level": 2
            },
            "transformedAttributes": {
              "content": "Bloc Galerie",
              "level": 2
            }
          }
        ]
      }
    ]
  }
}

さらなる例

このクエリでは、@underEachArrayItem@underJSONObjectProperty をラップし、さらに @underJSONObjectProperty@strUpperCase をラップすることで、WP REST APIを通じて取得した複数の投稿エントリの "title.rendered" プロパティを大文字に変換します:

query {
  postListData: _sendJSONObjectCollectionHTTPRequest(
    url: "https://newapi.getpop.org/wp-json/wp/v2/posts/?per_page=3&_fields=id,type,title,date"
  )
    @underEachArrayItem
      @underJSONObjectProperty(by: { path: "title.rendered" })
        @strUpperCase
}

...producing:

{
  "data": {
    "postListData": [
      {
        "id": 1692,
        "date": "2022-04-26T10:10:08",
        "type": "post",
        "title": {
          "rendered": "MY BLOGROLL"
        }
      },
      {
        "id": 1657,
        "date": "2020-12-21T08:24:18",
        "type": "post",
        "title": {
          "rendered": "A TALE OF TWO CITIES – TEASER"
        }
      },
      {
        "id": 1499,
        "date": "2019-08-08T02:49:36",
        "type": "post",
        "title": {
          "rendered": "COPE WITH WORDPRESS: POST DEMO CONTAINING PLENTY OF BLOCKS"
        }
      }
    ]
  }
}