スキーマチュートリアル
スキーマチュートリアルレッスン25: 外部APIのデータを変換する

レッスン25: 外部APIのデータを変換する

このチュートリアルレッスンでは、外部APIからのレスポンスを必要な形に適応させる例をご紹介します。

各エントリにデフォルト値と追加プロパティを付与する

REST APIエンドポイント newapi.getpop.org/wp-json/wp/v2/users/?_fields=id,name,url はユーザーデータを返しますが、一部のユーザーは url プロパティが空になっています。

[
  {
    "id": 1,
    "name": "leo",
    "url": "https://leoloso.com"
  },
  {
    "id": 7,
    "name": "Test",
    "url": ""
  },
  {
    "id": 2,
    "name": "Theme Demos",
    "url": ""
  }
]

以下のGraphQLクエリはこのレスポンスを変換します。

  • url プロパティが空のユーザーにデフォルトURLを追加する
  • 各ユーザーエントリに link プロパティを追加する(ユーザーの名前とURLの値を使って組み立てる)
query {
  # Retrieve data from the external API
  usersWithLinkAndDefaultURL: _sendJSONObjectCollectionHTTPRequest(
    input: {
      url: "https://newapi.getpop.org/wp-json/wp/v2/users/?_fields=id,name,url"
    }
  )
    # Set a default URL for users without any
    @underEachArrayItem
      @underJSONObjectProperty(
        by: {
          key: "url"
        }
      )
        @default(
          value: "https://mysite.com"
          condition: IS_EMPTY
        )
 
    # Add a new "link" entry on the JSON object
    @underEachArrayItem(
      affectDirectivesUnderPos: [1, 2, 3, 4],
      passValueOnwardsAs: "userListItem"
    )
      @applyField(
        name: "_objectProperty",
        arguments: {
          object: $userListItem,
          by: {
            key: "name"
          }
        },
        passOnwardsAs: "userName"
      )
      @applyField(
        name: "_objectProperty",
        arguments: {
          object: $userListItem,
          by: {
            key: "url"
          }
        },
        passOnwardsAs: "userURL"
      )
      @applyField(
        name: "_sprintf",
        arguments: {
          string: "<a href=\"%s\">%s</a>",
          values: [$userURL, $userName]
        },
        passOnwardsAs: "userLink"
      )
      @applyField(
        name: "_objectAddEntry",
        arguments: {
          object: $userListItem,
          key: "link",
          value: $userLink
        },
        setResultInResponse: true
      )
}

レスポンスは次のとおりです。

{
  "data": {
    "usersWithLinkAndDefaultURL": [
      {
        "id": 1,
        "name": "leo",
        "url": "https://leoloso.com",
        "link": "<a href=\"https://leoloso.com\">leo</a>"
      },
      {
        "id": 7,
        "name": "Test",
        "url": "https://mysite.com",
        "link": "<a href=\"https://mysite.com\">Test</a>"
      },
      {
        "id": 2,
        "name": "Theme Demos",
        "url": "https://mysite.com",
        "link": "<a href=\"https://mysite.com\">Theme Demos</a>"
      }
    ]
  }
}

コンポーザブルディレクティブは、1つ以上のディレクティブをネストできます。複数のディレクティブをネストする場合は、引数 affectDirectivesUnderPos を使って指定します。この引数には、そのディレクティブからネストされたディレクティブまでの相対位置が含まれます。

上記のGraphQLクエリでは、ディレクティブ @underEachArrayItemField Value Iteration and Manipulation エクステンションが提供)がコンポーザブルディレクティブです。最初の出現では1つのディレクティブのみをネストしているため、引数 affectDirectivesUnderPos は省略できます。

    @underEachArrayItem
      @underJSONObjectProperty(
        # ...
      )

(なお、@underJSONObjectProperty もコンポーザブルディレクティブであり、@default ディレクティブをネストしています。)

2回目の出現では、引数 affectDirectivesUnderPos に値 [1, 2, 3, 4] を指定することで、右側にある4つのディレクティブをネストしています。

    @underEachArrayItem(
      affectDirectivesUnderPos: [1, 2, 3, 4],
      # ...
    )
      @applyField(
        name: "_objectProperty",
        # ...
      )
      @applyField(
        name: "_objectProperty",
        # ...
      )
      @applyField(
        name: "_sprintf",
       # ...
      )
      @applyField(
        name: "_objectAddEntry",
        # ...
      )



🔥 ヒント:

ディレクティブ @applyFieldField on Field エクステンションが提供)には、出力の送り先が2つあります。

  • 引数 passOnwardsAs: "someVariableName" を指定すると、新しい値が動的変数 $someVariableName に代入され、後続のネストされたディレクティブから参照できます。
      @applyField(
        name: "_objectProperty",
        arguments: {
          object: $userListItem,
          by: {
            key: "name"
          }
        },
        passOnwardsAs: "userName"
      )
  • 引数 setResultInResponse: true を指定すると、新しい値がフィールドに再代入され(レスポンスが変更されます)。
      @applyField(
        name: "_objectAddEntry",
        arguments: {
          object: $userListItem,
          key: "link",
          value: $userLink
        },
        setResultInResponse: true
      )

JSONオブジェクトから特定のプロパティを抽出する

REST APIエンドポイント newapi.getpop.org/wp-json/newsletter/v1/subscriptions は、メール購読データのコレクションを返します。このデータには購読者のメールアドレスと言語が含まれています。

[
  {
    "email": "abracadabra@ganga.com",
    "lang": "de"
  },
  {
    "email": "longon@caramanon.com",
    "lang": "es"
  },
  {
    "email": "rancotanto@parabara.com",
    "lang": "en"
  },
  {
    "email": "quezarapadon@quebrulacha.net",
    "lang": "fr"
  },
  {
    "email": "test@test.com",
    "lang": "de"
  },
  {
    "email": "emilanga@pedrola.com",
    "lang": "fr"
  }
]

以下のGraphQLクエリは、各エントリから email プロパティを抽出してフィールド値を置き換えることで、APIレスポンスからメールアドレスのみを出力します。

query {
  emails: _sendJSONObjectCollectionHTTPRequest(
    input: {
      url: "https://newapi.getpop.org/wp-json/newsletter/v1/subscriptions"
    }
  )
    @underEachArrayItem(
      passValueOnwardsAs: "userEntry"
    )
      @applyField(
        name: "_objectProperty"
        arguments: {
          object: $userEntry,
          by: {
            key: "email"
          }
        }
        setResultInResponse: true
      )
}

レスポンスは次のとおりです。

{
  "data": {
    "emails": [
      "abracadabra@ganga.com",
      "longon@caramanon.com",
      "rancotanto@parabara.com",
      "quezarapadon@quebrulacha.net",
      "test@test.com",
      "emilanga@pedrola.com"
    ]
  }
}

条件に応じてフィールド値を変更する

この例は前の例を引き継ぎ、さらにレスポンス内のメールアドレスの形式を変換します。

以下のGraphQLクエリは、APIレスポンスからメールアドレスを抽出し、コンポーザブルディレクティブ @ifConditional Field Manipulation エクステンションが提供)を使って、言語が英語またはドイツ語のユーザーのメールアドレスを大文字に変換します。

query {
  # Retrieve data from a REST API endpoint
  userEntries: _sendJSONObjectCollectionHTTPRequest(
    input: {
      url: "https://newapi.getpop.org/wp-json/newsletter/v1/subscriptions"
    }
  )
    @remove
 
  emails: _echo(value: $__userEntries)
 
    # Iterate all the entries, passing every entry
    # (under the dynamic variable $userEntry)
    # to each of the next 4 directives
    @underEachArrayItem(
      passValueOnwardsAs: "userEntry"
      affectDirectivesUnderPos: [1, 2, 3, 4]
    )
 
      # Extract property "lang" from the entry
      # via the functionality field `_objectProperty`,
      # and pass it onwards as dynamic variable $userLang
      @applyField(
        name: "_objectProperty"
        arguments: {
          object: $userEntry,
          by: {
            key: "lang"
          }
        }
        passOnwardsAs: "userLang"
      )
 
      # Execute functionality field `_inArray` to find out
      # if $userLang is either "en" or "de", and place the
      # result under dynamic variable $isSpecialLang
      @applyField(
        name: "_inArray"
        arguments: {
          value: $userLang,
          array: ["en", "de"]
        }
        passOnwardsAs: "isSpecialLang"
      )
 
      # Extract property "email" from the entry
      # and set it back as the value for that entry
      @applyField(
        name: "_objectProperty"
        arguments: {
          object: $userEntry,
          by: {
            key: "email"
          }
        }
        setResultInResponse: true
      )
 
      # If $isSpecialLang is `true` then execute
      # directive `@strUpperCase` 
      @if(condition: $isSpecialLang)
        @strUpperCase
}

レスポンスは次のとおりです。

{
  "data": {
    "emails": [
      "ABRACADABRA@GANGA.COM",
      "longon@caramanon.com",
      "RANCOTANTO@PARABARA.COM",
      "quezarapadon@quebrulacha.net",
      "TEST@TEST.COM",
      "emilanga@pedrola.com"
    ]
  }
}

Gato GraphQLでの条件ロジックの実行は動的にできます。クエリ対象のオブジェクトで評価された動的変数を @if(condition:)(および @unless(condition:))に渡すことで、そのエンティティの条件に応じてロジックが実行されるかどうかが決まります。

これにより、以下のような条件に基づいて、一部のエンティティに対してのみ動的にレスポンスを変更できます。

  • 投稿にコメントがあるか?
  • コメントに返信があるか?
  • ユーザーは管理者か?
  • タグ・カテゴリが何らかの投稿に適用されているか?
  • その他