热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

[译+]LaravelGraphQLReadMe文档

原文地址:readme.mdadvanced.md使用语法Schemas从1.0版本开始,可以定义多个语法,如果您想要一个公共的入口,另一个需要身份验证的入口,那么拥有多个语法是非

原文地址:

  • readme.md
  • advanced.md

使用

语法 / Schemas

从 1.0 版本开始, 可以定义多个语法, 如果您想要一个公共的入口,另一个需要身份验证的入口,那么拥有多个语法是非常有用的。

您可以在配置中定义多个语法:

'schema' => 'default',
'schemas' => [
'default' => [
'query' => [
//'users' => 'App\GraphQL\Query\UsersQuery'
],
'mutation' => [
//'updateUserEmail' => 'App\GraphQL\Query\UpdateUserEmailMutation'
]
],
'secret' => [
'query' => [
//'users' => 'App\GraphQL\Query\UsersQuery'
],
'mutation' => [
//'updateUserEmail' => 'App\GraphQL\Query\UpdateUserEmailMutation'
]
]
]

或者可以使用 facade 来添加语法

GraphQL::addSchema('secret', [
'query' => [
'users' => 'App\GraphQL\Query\UsersQuery'
],
'mutation' => [
'updateUserEmail' => 'App\GraphQL\Query\UpdateUserEmailMutation'
]
]);

随后, 你可以使用 facade 来创建语法

// Will return the default schema defined by 'schema' in the config
$schema = GraphQL::schema();
// Will return the 'secret' schema
$schema = GraphQL::schema('secret');
// Will build a new schema
$schema = GraphQL::schema([
'query' => [
//'users' => 'App\GraphQL\Query\UsersQuery'
],
'mutation' => [
//'updateUserEmail' => 'App\GraphQL\Query\UpdateUserEmailMutation'
]
]);

你可以通过指定的语法来访问

// Default schema
http://homestead.app/graphql?query=query+FetchUsers{users{id,email}}
// Secret schema
http://homestead.app/graphql/secret?query=query+FetchUsers{users{id,email}}

创建查询

首先你需要创建一个类型

namespace App\GraphQL\Type;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Type as GraphQLType;
class UserType extends GraphQLType
{
protected $attributes = [
'name' => 'User',
'description' => 'A user'
];
/*
* Uncomment following line to make the type input object.
* http://graphql.org/learn/schema/#input-types
*/
// protected $inputObject = true;
public function fields()
{
return [
'id' => [
'type' => Type::nonNull(Type::string()),
'description' => 'The id of the user'
],
'email' => [
'type' => Type::string(),
'description' => 'The email of user'
]
];
}
// If you want to resolve the field yourself, you can declare a method
// with the following format resolve[FIELD_NAME]Field()
protected function resolveEmailField($root, $args)
{
return strtolower($root->email);
}
}

然后将类型添加到 config/graphql.php 文件中

'types' => [
'User' => 'App\GraphQL\Type\UserType'
]

你也可以使用 GraphQL Facade 来进行添加, 添加到 service provider 中

GraphQL::addType('App\GraphQL\Type\UserType', 'User');

然后, 你需要定义一个查询并且返回这个类型(或者列表). 你同样也可以在指定的参数, 这些参数可以用在 resolve 方法中.

namespace App\GraphQL\Query;
use GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Query;
use App\User;
class UsersQuery extends Query
{
protected $attributes = [
'name' => 'users'
];
public function type()
{
return Type::listOf(GraphQL::type('User'));
}
public function args()
{
return [
'id' => ['name' => 'id', 'type' => Type::string()],
'email' => ['name' => 'email', 'type' => Type::string()]
];
}
public function resolve($root, $args)
{
if (isset($args['id'])) {
return User::where('id' , $args['id'])->get();
} else if(isset($args['email'])) {
return User::where('email', $args['email'])->get();
} else {
return User::all();
}
}
}

添加 query 到 config/graphql.php 文件中

'schemas' => [
'default' => [
'query' => [
'users' => 'App\GraphQL\Query\UsersQuery'
],
// ...
]
]

这样就OK了, 你可以使用 /graphql 来进行查询了. 尝试使用 get 请求来获取下数据

query FetchUsers {
users {
id
email
}
}

或者使用 url 地址来进行请求

http://homestead.app/graphql?query=query+FetchUsers{users{id,email}}

创建修改

更改就是另外一种形式的查询, 他接受参数(用来进行更改或者创建使用的)并且返回一个对象或者指定的类型

例如使用修改来更新用户的密码, 首先你需要定义 mutation

namespace App\GraphQL\Mutation;
use GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Mutation;
use App\User;
class UpdateUserPasswordMutation extends Mutation
{
protected $attributes = [
'name' => 'updateUserPassword'
];
public function type()
{
return GraphQL::type('User');
}
public function args()
{
return [
'id' => ['name' => 'id', 'type' => Type::nonNull(Type::string())],
'password' => ['name' => 'password', 'type' => Type::nonNull(Type::string())]
];
}
public function resolve($root, $args)
{
$user = User::find($args['id']);
if (!$user) {
return null;
}
$user->password = bcrypt($args['password']);
$user->save();
return $user;
}
}

就想 resolve 方法. 你使用参数来更新你的模型并且返回她.

然后添加 mutation 到 config/graphql.php 文件中

'schema' => [
'default' => [
'mutation' => [
'updateUserPassword' => 'App\GraphQL\Mutation\UpdateUserPasswordMutation'
],
// ...
]
]

你可以使用如下的查询来进行修改

mutation users {
updateUserPassword(id: "1", password: "newpassword") {
id
email
}
}

url 中可以如下请求

http://homestead.app/graphql?query=mutation+users{updateUserPassword(id: "1", password: "newpassword"){id,email}}

添加修改验证

在修改中增加验证是可以的. 老铁. 它使用 laravel Validator 来处理验证并且返回相应的参数.

当创建 mutation 的时候, 你可以添加如下方法来定义验证规则:

namespace App\GraphQL\Mutation;
use GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Mutation;
use App\User;
class UpdateUserEmailMutation extends Mutation
{
protected $attributes = [
'name' => 'UpdateUserEmail'
];
public function type()
{
return GraphQL::type('User');
}
public function args()
{
return [
'id' => ['name' => 'id', 'type' => Type::string()],
'email' => ['name' => 'email', 'type' => Type::string()]
];
}
public function rules()
{
return [
'id' => ['required'],
'email' => ['required', 'email']
];
}
public function resolve($root, $args)
{
$user = User::find($args['id']);
if (!$user) {
return null;
}
$user->email = $args['email'];
$user->save();
return $user;
}
}

同样, 你可以在参数中定义规则:

class UpdateUserEmailMutation extends Mutation
{
//...
public function args()
{
return [
'id' => [
'name' => 'id',
'type' => Type::string(),
'rules' => ['required']
],
'email' => [
'name' => 'email',
'type' => Type::string(),
'rules' => ['required', 'email']
]
];
}
//...
}

当你执行修改的时候, 会返回验证错误. 由于 GraphQL 规范定义了错误的格式,因此会将验证错误消息作为额外的 validation 属性添加到错误对象中。为了找到验证错误,应该检查一个 message 等于 validation 的时候,然后 validation 属性将包含 Laravel Validator 返回的正常错误消息信息.

{
"data": {
"updateUserEmail": null
},
"errors": [
{
"message": "validation",
"locations": [
{
"line": 1,
"column": 20
}
],
"validation": {
"email": [
"The email is invalid."
]
}
}
]
}

高级用法

查询变量

GraphQL 允许你使用变量来查询数据, 从而不用在查询中硬编码值. 如下

query FetchUserByID($id: String) {
user(id: $id) {
id
email
}
}

当你查询 GraphQL 的时候可以传递 variables 参数

http://homestead.app/graphql?query=query+FetchUserByID($id:String){user(id:$id){id,email}}&variables={"id":"1"}

查询嵌入资源

如果想查询嵌入资源

query FetchUser{
user(id: 123456789) {
id
posts(id: 987654321) {
id
}
}
}

你需要在 UserType 中添加 post 字段并且实现 resolveField 方法

public function fields()
{
return [
'id' => [
'type' => Type::nonNull(Type::string()),
'description' => 'Id of user',
],
'posts' => [
'args' => [
'id' => [
'type' => Type::string(),
'description' => 'id of the post',
],
],
'type' => Type::listOf(GraphQL::type('Post')),
'description' => 'post description',
],
];
}public function resolvePostsField($root, $args)
{
if (isset($args['id'])) {
return $root->posts->where('id', $args['id']);
}
return $root->posts;
}

枚举

美剧类型是一个特殊类型的标量变量, 用来限制一系列的允许的数据, 可以查看这里阅读更多的信息

首先创建一个 Enum 作为 GraphQLType 的扩展类型

// app/GraphQL/Enums/EpisodeEnum.php
namespace App\GraphQL\Enums;
use Folklore\GraphQL\Support\Type as GraphQLType;
class EpisodeEnum extends GraphQLType {
protected $enumObject = true;
protected $attributes = [
'name' => 'Episode',
'description' => 'The types of demographic elements',
'values' => [
'NEWHOPE' => 'NEWHOPE',
'EMPIRE' => 'EMPIRE',
'JEDI' => 'JEDI',
],
];
}

注册 Enum 在 config/graphql.phptypes 数组

// config/graphql.php
'types' => [TestEnum' => TestEnumType::class ];

然后如下使用

// app/GraphQL/Type/TestType.php
class TestType extends GraphQLType {
public function fields()
{
return [
'type' => [
'type' => GraphQL::type('TestEnum')
]
]
}
}

接口

你可以使用接口来限制一系列的字段, 阅读更多的消息点击这里

一系列的接口

// app/GraphQL/Interfaces/CharacterInterface.php
namespace App\GraphQL\Interfaces;
use GraphQL;
use Folklore\GraphQL\Support\InterfaceType;
use GraphQL\Type\Definition\Type;
class CharacterInterface extends InterfaceType {
protected $attributes = [
'name' => 'Character',
'description' => 'Character interface.',
]; public function fields() {
return [
'id' => [
'type' => Type::nonNull(Type::int()),
'description' => 'The id of the character.'
],
'appearsIn' => [
'type' => Type::nonNull(Type::listOf(GraphQL::type('Episode'))),
'description' => 'A list of episodes in which the character has an appearance.'
],
];
} public function resolveType($root) {
// Use the resolveType to resolve the Type which is implemented trough this interface
$type = $root['type'];
if ($type === 'human') {
return GraphQL::type('Human');
} else if ($type === 'droid') {
return GraphQL::type('Droid');
}
}
}

类型实现

// app/GraphQL/Types/HumanType.php
namespace App\GraphQL\Types;
use GraphQL;
use Folklore\GraphQL\Support\Type as GraphQLType;
use GraphQL\Type\Definition\Type;
class HumanType extends GraphQLType {
protected $attributes = [
'name' => 'Human',
'description' => 'A human.'
];
public function fields() {
return [
'id' => [
'type' => Type::nonNull(Type::int()),
'description' => 'The id of the human.',
],
'appearsIn' => [
'type' => Type::nonNull(Type::listOf(GraphQL::type('Episode'))),
'description' => 'A list of episodes in which the human has an appearance.'
],
'totalCredits' => [
'type' => Type::nonNull(Type::int()),
'description' => 'The total amount of credits this human owns.'
]
];
}
public function interfaces() {
return [
GraphQL::type('Character')
];
}
}

自定义字段

你同样可以定义一个字段类, 如果你想在多个类型中重用他们.

namespace App\GraphQL\Fields;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Field;
class PictureField extends Field {
protected $attributes = [
'description' => 'A picture'
];
public function type(){
return Type::string();
}
public function args()
{
return [
'width' => [
'type' => Type::int(),
'description' => 'The width of the picture'
],
'height' => [
'type' => Type::int(),
'description' => 'The height of the picture'
]
];
}
protected function resolve($root, $args)
{
$width = isset($args['width']) ? $args['width']:100;
$height = isset($args['height']) ? $args['height']:100;
return 'http://placehold.it/'.$width.'x'.$height;
}
}

你可以在 type 声明中使用他们

namespace App\GraphQL\Type;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Type as GraphQLType;
use App\GraphQL\Fields\PictureField;
class UserType extends GraphQLType {
protected $attributes = [
'name' => 'User',
'description' => 'A user'
];
public function fields()
{
return [
'id' => [
'type' => Type::nonNull(Type::string()),
'description' => 'The id of the user'
],
'email' => [
'type' => Type::string(),
'description' => 'The email of user'
],
//Instead of passing an array, you pass a class path to your custom field
'picture' => PictureField::class
];
}
}

加载关联关系

传递给 query 的 resolve 方法的第三个参数是 GraphQL\Type\Definition\ResolveInfo 的实例, 允许你从请求中取回指定的 key. 下面是一个使用这个参数的例子来获取关联模型的数据. 如下

namespace App\GraphQL\Query;
use GraphQL;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ResolveInfo;
use Folklore\GraphQL\Support\Query;
use App\User;
class UsersQuery extends Query
{
protected $attributes = [
'name' => 'Users query'
];
public function type()
{
return Type::listOf(GraphQL::type('user'));
}
public function args()
{
return [
'id' => ['name' => 'id', 'type' => Type::string()],
'email' => ['name' => 'email', 'type' => Type::string()]
];
}
public function resolve($root, $args, $context, ResolveInfo $info)
{
$fields = $info->getFieldSelection($depth = 3);
$users = User::query();
foreach ($fields as $field => $keys) {
if ($field === 'profile') {
$users->with('profile');
}
if ($field === 'posts') {
$users->with('posts');
}
}
return $users->get();
}
}

你的 UserType 可能看起来是这个样子的

namespace App\GraphQL\Type;
use Folklore\GraphQL\Support\Facades\GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Type as GraphQLType;
class UserType extends GraphQLType
{
/**
* @var array
*/
protected $attributes = [
'name' => 'User',
'description' => 'A user',
];
/**
* @return array
*/
public function fields()
{
return [
'uuid' => [
'type' => Type::nonNull(Type::string()),
'description' => 'The uuid of the user'
],
'email' => [
'type' => Type::nonNull(Type::string()),
'description' => 'The email of user'
],
'profile' => [
'type' => GraphQL::type('Profile'),
'description' => 'The user profile',
],
'posts' => [
'type' => Type::listOf(GraphQL::type('Post')),
'description' => 'The user posts',
]
];
}
}

这样我们有一个 profile 和一个 post 类型作为期待的返回关联关系数据

class ProfileType extends GraphQLType
{
protected $attributes = [
'name' => 'Profile',
'description' => 'A user profile',
];
public function fields()
{
return [
'name' => [
'type' => Type::string(),
'description' => 'The name of user'
]
];
}
}

class PostType extends GraphQLType
{
protected $attributes = [
'name' => 'Post',
'description' => 'A post',
];
public function fields()
{
return [
'title' => [
'type' => Type::nonNull(Type::string()),
'description' => 'The title of the post'
],
'body' => [
'type' => Type::string(),
'description' => 'The body the post'
]
];
}
}

最后你的查询可能是这个样子, 使用 URL

http://homestead.app/graphql?query=query+FetchUsers{users{uuid, email, team{name}}}

推荐阅读
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • 不同优化算法的比较分析及实验验证
    本文介绍了神经网络优化中常用的优化方法,包括学习率调整和梯度估计修正,并通过实验验证了不同优化算法的效果。实验结果表明,Adam算法在综合考虑学习率调整和梯度估计修正方面表现较好。该研究对于优化神经网络的训练过程具有指导意义。 ... [详细]
  • 本文讨论了在openwrt-17.01版本中,mt7628设备上初始化启动时eth0的mac地址总是随机生成的问题。每次随机生成的eth0的mac地址都会写到/sys/class/net/eth0/address目录下,而openwrt-17.01原版的SDK会根据随机生成的eth0的mac地址再生成eth0.1、eth0.2等,生成后的mac地址会保存在/etc/config/network下。 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • 本文介绍了在使用Laravel和sqlsrv连接到SQL Server 2016时,如何在插入查询中使用输出子句,并返回所需的值。同时讨论了使用CreatedOn字段返回最近创建的行的解决方法以及使用Eloquent模型创建后,值正确插入数据库但没有返回uniqueidentifier字段的问题。最后给出了一个示例代码。 ... [详细]
  • laravel 使用腾讯云 COS5全教程
    laravel使用腾讯云COS5全教程一下载首先第一步肯定是用composer把包安装下来,这里是laravel5.8版本的,所以我用的是cos5 ... [详细]
  • SpringBoot整合GraphQL第(二)章节
    Postman请求方式Post请求JSON格式传递{query:{selectUserById(id:1){idnameecountlout}}}根据id进行查询组 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • 本文介绍了南邮ctf-web的writeup,包括签到题和md5 collision。在CTF比赛和渗透测试中,可以通过查看源代码、代码注释、页面隐藏元素、超链接和HTTP响应头部来寻找flag或提示信息。利用PHP弱类型,可以发现md5('QNKCDZO')='0e830400451993494058024219903391'和md5('240610708')='0e462097431906509019562988736854'。 ... [详细]
  • 3.223.28周学习总结中的贪心作业收获及困惑
    本文是对3.223.28周学习总结中的贪心作业进行总结,作者在解题过程中参考了他人的代码,但前提是要先理解题目并有解题思路。作者分享了自己在贪心作业中的收获,同时提到了一道让他困惑的题目,即input details部分引发的疑惑。 ... [详细]
  • PDO MySQL
    PDOMySQL如果文章有成千上万篇,该怎样保存?数据保存有多种方式,比如单机文件、单机数据库(SQLite)、网络数据库(MySQL、MariaDB)等等。根据项目来选择,做We ... [详细]
  • 本文介绍了在iOS开发中使用UITextField实现字符限制的方法,包括利用代理方法和使用BNTextField-Limit库的实现策略。通过这些方法,开发者可以方便地限制UITextField的字符个数和输入规则。 ... [详细]
  • Android工程师面试准备及设计模式使用场景
    本文介绍了Android工程师面试准备的经验,包括面试流程和重点准备内容。同时,还介绍了建造者模式的使用场景,以及在Android开发中的具体应用。 ... [详细]
  • Demoshttps://v2-mst-aptd-at-lcz-sty.vercel.app/usesthelatestbr ... [详细]
author-avatar
80后女孩香香521
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有