Schema 教程
Schema 教程第26课:过滤来自外部 API 的数据

第26课:过滤来自外部 API 的数据

如果外部 API 不支持按某个所需属性进行过滤,我们可以使用 Gato GraphQL 遍历 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 query 通过以下步骤过滤掉 url 属性为空的用户:

  • 从外部 API 获取数据
  • 通过 @underEachArrayItem 遍历条目,并将每个条目存入动态变量 $userDataEntry
  • 从每个条目中提取 url 属性,并将该值存入动态变量 $websiteURL
  • 检查该值是否为空,并将结果赋值给动态变量 $isWebsiteURLEmpty
  • 应用条件指令 @if,当 $isWebsiteURLEmptytrue 时,将该条目的值设为 null
  • 执行指令 @arrayFilter 过滤掉所有 null 条目
query {
  usersWithWebsiteURL: _sendJSONObjectCollectionHTTPRequest(
    input: {
      url: "https://newapi.getpop.org/wp-json/wp/v2/users/?_fields=id,name,url"
    }
  )
    # Remove users without a website URL
    @underEachArrayItem(
      passValueOnwardsAs: "userDataEntry"
      affectDirectivesUnderPos: [1, 2, 3]
    )
      @applyField(
        name: "_objectProperty"
        arguments: {
          object: $userDataEntry
          by: {
            key: "url"
          }
        }
        passOnwardsAs: "websiteURL"
      )
      @applyField(
        name: "_isEmpty"
        arguments: {
          value: $websiteURL
        }
        passOnwardsAs: "isWebsiteURLEmpty"
      )
      @if(
        condition: $isWebsiteURLEmpty
      )
        @setNull
    @arrayFilter
}

响应结果如下:

{
  "data": {
    "usersWithWebsiteURL": [
      {
        "id": 1,
        "name": "leo",
        "url": "https://leoloso.com"
      }
    ]
  }
}