บทช่วยสอน Schema
บทช่วยสอน Schemaบทเรียนที่ 26: การกรองข้อมูลจาก API ภายนอก

บทเรียนที่ 26: การกรองข้อมูลจาก API ภายนอก

หาก API ภายนอกไม่อนุญาตให้กรองตามคุณสมบัติบางอย่างที่เราต้องการ เราสามารถใช้ Gato GraphQL เพื่อวนซ้ำรายการต่าง ๆ ในผลลัพธ์ของ API และลบรายการที่ไม่ตรงตามเงื่อนไขของเราออกได้

ลองอ้างอิงถึง REST API endpoint 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
  • ใช้ directive แบบมีเงื่อนไข @if ซึ่งหาก $isWebsiteURLEmpty เป็น true จะกำหนดค่าของรายการนั้นเป็น null
  • เรียกใช้ directive @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"
      }
    ]
  }
}