Thư viện QueriesBổ sung dữ liệu từ API bên ngoài
Bổ sung dữ liệu từ API bên ngoài
Nếu chúng ta cần lấy dữ liệu từ API bên ngoài nhưng cần sửa đổi kết quả theo một cách nào đó (chẳng hạn như cung cấp giá trị mặc định khi một trường bị trống), thì chúng ta có thể sử dụng Gato GraphQL để triển khai một API gateway giúp chuyển đổi các mục theo yêu cầu.
Ví dụ, khi gọi endpoint REST API /users từ một trang WordPress, chúng ta có thể thêm giá trị mặc định khi trường url bị trống, và một thuộc tính link bổ sung với mã HTML:
query FilterDataFromWordPressAPI(
# eg: https://somesite.com/wp-json/wp/v2/users/?_fields=id,name,url
$endpointURL: URL!
) {
usersWithLinkAndDefaultURL: _sendJSONObjectCollectionHTTPRequest(
input: {
url: $endpointURL
}
)
# 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
)
}