Directives
内置指令
该指令是客户端为 GraphQL 服务器提供附加上下文以及如何执行查询的提示的一种方式。指令可以附加到字段或片段上,并且可以以任何方式影响查询的执行。
GraphQL 规范包含两个内置指令:
- @include(if: Boolean) 如果参数为 true,则只在结果中包含此字段或片段
- @skip(if: Boolean) 如果参数为 true,则跳过此字段或片段
例如:
query Hero($episode: Episode, $withFriends: Boolean!) {
hero(episode: $episode) {
name
friends @include(if: $withFriends) {
name
}
}
}
在这里,如果 $withFriends 变量设置为 false - friends
部分将被忽略并从响应中排除。重要的实现细节:这些字段永远不会被执行(不仅仅是在执行后从响应中移除)。
自定义指令
graphql-php 支持自定义指令,即使它们的存在不影响字段的执行。但是你可以在字段解析器中使用 GraphQL\Type\Definition\ResolveInfo
,以根据这些指令修改输出或执行统计信息收集。
其他用例是您自己的依赖于自定义指令的查询验证规则。
在 graphql-php 中,自定义指令是一个 GraphQL\Type\Definition\Directive
(或其中一个子类)的实例,它接受以下选项的数组:
<?php
use GraphQL\Language\DirectiveLocation;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\Directive;
use GraphQL\Type\Definition\FieldArgument;
$trackDirective = new Directive([
'name' => 'track',
'description' => 'Instruction to record usage of the field by client',
'locations' => [
DirectiveLocation::FIELD,
],
'args' => [
new FieldArgument([
'name' => 'details',
'type' => Type::string(),
'description' => 'String with additional details of field usage scenario',
'defaultValue' => ''
])
]
]);
请参阅可能的指令位置 GraphQL\Type\Definition\DirectiveLocation
。
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。