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

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/graphql-php/typ...

译文地址:https://learnku.com/docs/graphql-php/typ...

上一篇 下一篇
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
贡献者:2
讨论数量: 0
发起讨论 只看当前版本


暂无话题~