บทช่วยสอน 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"
}
]
}
}