配置 Schema使用"field to input"
使用"field to input"
在同一个 Query 中获取某个字段的值、对其进行处理,并将其作为输入传递给另一个字段。
使用方法
要引用某个字段的值,需使用"Variable"语法 $,并在字段别名或名称前加上 __。(例如,excerpt 字段的值引用为 $__excerpt。)第二个字段的响应本身也可以作为另一个字段的输入:
{
posts {
excerpt
# Referencing previous field with name "excerpt"
isEmptyExcerpt: _isEmpty(value: $__excerpt)
# Referencing previous field with alias "isEmptyExcerpt"
isNotEmptyExcerpt: _not(value: $__isEmptyExcerpt)
}
}响应结果如下:
{
"data": {
"posts": [
{
"excerpt": "Some post excerpt",
"isEmptyExcerpt": false,
"isNotEmptyExcerpt": true
},
{
"excerpt": "",
"isEmptyExcerpt": true,
"isNotEmptyExcerpt": false
}
]
}
}字段只能被同一节点中位于其之前的兄弟字段引用。以下 Query 将无法正常工作:
# This will fail because the reference to the field must appear after the field, not before
{
posts {
isEmptyExcerpt: _isEmpty(value: $__excerpt)
excerpt
}
}
# This will fail because the reference must be done within the same node
{
posts {
excerpt
}
isEmptyExcerpt: _isEmpty(value: $__excerpt)
}字段也不能从指令参数中引用(如需此功能,请使用 @passOnwards 指令):
# This will fail because the reference can be only used as input to a field, not to a directive
{
posts {
hasComments
title @include(if: $__hasComments)
}
}示例
如果文章摘要为空,则改用标题:
{
posts {
title
originalExcerpt: excerpt
isEmptyExcerpt: _isEmpty(value: $__originalExcerpt)
excerpt: if(condition: $__isEmptyExcerpt, then: $__title, else: $__originalExcerpt)
}
}从外部 REST 端点获取数据,并根据需求对数据进行处理。
{
externalData: _getJSON(url: "https://example.com/rest/some-external-endpoint")
userName: _extract(object: $__externalData, path: "data.user.name")
userLastName: _extract(object: $__externalData, path: "data.user.surname")
}这将产生以下结果:
{
"data": {
"externalData": {
"data": {
"user": {
"id": 1,
"name": "Leo",
"surname": "Loso"
}
}
},
"userName": "Leo",
"userLastName": "Loso"
}
}对 externalData 使用 @remove 指令,还可以避免在响应中输出外部端点的原始数据:
{
externalData: _getJSON(url: "https://example.com/rest/some-external-endpoint") @remove
userName: _extract(object: $__externalData, path: "data.user.name")
userLastName: _extract(object: $__externalData, path: "data.user.surname")
}这将产生以下结果:
{
"data": {
"userName": "Leo",
"userLastName": "Loso"
}
}获取每位用户中提及该用户邮箱的文章:
{
users {
email
posts(filter: { search: $__email }) {
id
title
}
}
}通过 optionValue 字段定义 to 和 from 邮箱地址,并发送新闻通讯:
mutation {
fromEmail: optionValue(name: "admin_email")
toEmail: optionValue(name: "subscribers_email_list_recipient_address")
_sendEmail(
from: {
email: $__fromEmail
}
to: $__toEmail
subject: "Weekly summary"
messageAs: {
html: "..."
}
)
}Prev