本文字數:7134,大概需要14.27分鐘。
按照官網所述的:
A query language for your API一種用于 API 的查詢語言
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
GraphQL 既是一種用于 API 的查詢語言也是一個滿足你數據查詢的運行時。 GraphQL 對你的 API 中的數據提供了一套易于理解的完整描述,使得客戶端能夠準確地獲得它需要的數據,而且沒有任何冗余,也讓 API 更容易地隨著時間推移而演進,還能用于構建強大的開發者工具。
主要有以下幾個特點:
請求你所要的數據不多不少。向你的 API 發出一個 GraphQL 請求就能準確獲得你想要的數據,不多不少。 GraphQL 查詢總是返回可預測的結果。
獲取多個資源只用一個請求。GraphQL 查詢不僅能夠獲得資源的屬性,還能沿著資源間引用進一步查詢。典型的 REST API 請求多個資源時得載入多個 URL,而 GraphQL 可以通過一次請求就獲取你應用所需的所有數據。這樣一來,即使是比較慢的移動網絡連接下,使用 GraphQL 的應用也能表現得足夠迅速。
描述所有的可能類型系統。GraphQL API 基于類型和字段的方式進行組織,而非入口端點。你可以通過一個單一入口端點得到你所有的數據能力。GraphQL 使用類型來保證應用只請求可能的數據,還提供了清晰的輔助性錯誤信息。應用可以使用類型,而避免編寫手動解析代碼。
API 演進無需劃分版本。給你的 GraphQL API 添加字段和類型而無需影響現有查詢。老舊的字段可以廢棄,從工具中隱藏。通過使用單一演進版本,GraphQL API 使得應用始終能夠使用新的特性,并鼓勵使用更加簡潔、更好維護的服務端代碼。
使用你現有的數據和代碼。GraphQL 讓你的整個應用共享一套 API,而不用被限制于特定存儲引擎。GraphQL 引擎已經有多種語言實現,通過 GraphQL API 能夠更好利用你的現有數據和代碼。你只需要為類型系統的字段編寫函數,GraphQL 就能通過優化并發的方式來調用它們。
Demo
先寫一個 Demo 來看看如何結合 Laravel 使用 GraphQL。
引入 rebing/graphql-laravel
composer require "rebing/graphql-laravel"
因為 Laravel 5.5 開始,有「包自動發現」http://mp.weixin.qq.com/s/AD05BiKjPsI2ehC-mhQJQw功能,所以 Laravel 5.5 可以不用手動引入該 provider 和 aliase。之前的版本需要引入對應的 provider 和 aliase。
"extra": { ? ?"laravel": { ? ? ? ?"providers": [ ? ? ? ? ? ?"Rebing\\GraphQL\\GraphQLServiceProvider" ? ? ? ?], ? ? ? ?"aliases": { ? ? ? ? ? ?"GraphQL": "Rebing\\GraphQL\\Support\\Facades\\GraphQL" ? ? ? ?} ? ?}}
創建 Type 和 Query
Type: 通過 Type,可以幫助我們格式化查詢結果的類型,主要有 boolean、string、float、int 等,同時也可以自定義類型
Query: 通過 Query,可以獲取我們需要的數據。
在項目根目錄創建 GraphQL 文件件用于存放 Type 和 Query
定義 UsersType:
<?php /** * User: yemeishu */namespace App\GraphQL\Type;use App\User;use GraphQL\Type\Definition\Type;use Rebing\GraphQL\Support\Facades\GraphQL;use Rebing\GraphQL\Support\Type as GraphQLType;classUsersTypeextendsGraphQLType{ ? ?protected $attributes = [ ? ? ? ?'name' => 'Users', ? ? ? ?'description' => 'A type', ? ? ? ?'model' => User::class, // define model for users type ? ?]; ? ?// define field of type ? ?public functionfields(){ ? ? ? ?return [ ? ? ? ? ? ?'id' => [ ? ? ? ? ? ? ? ?'type' => Type::nonNull(Type::int()), ? ? ? ? ? ? ? ?'description' => 'The id of the user' ? ? ? ? ? ?], ? ? ? ? ? ?'email' => [ ? ? ? ? ? ? ? ?'type' => Type::string(), ? ? ? ? ? ? ? ?'description' => 'The email of user' ? ? ? ? ? ?], ? ? ? ? ? ?'name' => [ ? ? ? ? ? ? ? ?'type' => Type::string(), ? ? ? ? ? ? ? ?'description' => 'The name of the user' ? ? ? ? ? ?] ? ? ? ?]; ? ?} ? ?protected functionresolveEmailField($root, $args){ ? ? ? ?return strtolower($root->email); ? ?}}
定義 Query:
<?php /** * User: yemeishu */namespace App\GraphQL\Query;use App\User;use GraphQL\Type\Definition\Type;use Rebing\GraphQL\Support\Facades\GraphQL;use Rebing\GraphQL\Support\Query;use Rebing\GraphQL\Support\SelectFields;classUsersQueryextendsQuery{ ? ?protected $attributes = [ ? ? ? ?'name' => 'users', ? ? ? ?'description' => 'A query of users' ? ?]; ? ?public functiontype(){ ? ? ? ?return Type::listOf(GraphQL::type('users')); ? ?} ? ?// arguments to filter query ? ?public functionargs(){ ? ? ? ?return [ ? ? ? ? ? ?'id' => [ ? ? ? ? ? ? ? ?'name' => 'id', ? ? ? ? ? ? ? ?'type' => Type::int() ? ? ? ? ? ?], ? ? ? ? ? ?'email' => [ ? ? ? ? ? ? ? ?'name' => 'email', ? ? ? ? ? ? ? ?'type' => Type::string() ? ? ? ? ? ?] ? ? ? ?]; ? ?} ? ?public functionresolve($root, $args, SelectFields $fields){ ? ? ? ?$where = function($query)use($args){ ? ? ? ? ? ?if (isset($args['id'])) { ? ? ? ? ? ? ? ?$query->where('id',$args['id']); ? ? ? ? ? ?} ? ? ? ? ? ?if (isset($args['email'])) { ? ? ? ? ? ? ? ?$query->where('email',$args['email']); ? ? ? ? ? ?} ? ? ? ?}; ? ? ? ?$users = User::with(array_keys($fields->getRelations())) ? ? ? ? ? ?->where($where) ? ? ? ? ? ?->select($fields->getSelect()) ? ? ? ? ? ?->get(); ? ? ? ?return $users; ? ?}}
配置 graphql.php
將寫好的 UsersType 和 UsersQuery 注冊到 GraphGL 配置文件中。
測試
我們主要有兩種途徑用于測試,第一種就是向測試 RESTful 接口一樣,使用 Postman:
另一種方式就是利用 GraphiQL:
An in-browser IDE for exploring GraphQL.https://github.com/graphql/graphiql
這里我們使用noh4ck/graphiql
// 1. 安裝插件composer require "noh4ck/graphiql:@dev"// 2. 加入 providerGraphiql\GraphiqlServiceProvider::class// 3. 命令artisan graphiql:publish
配置文件可看出 route 為:/graphql-ui
運行結果:
還可以通過傳入參數 (id: 1) 來篩選數據:
Mutation
通過 Demo,我們初步了解 GraphQL 的 Query 查詢方法,接下來我們看看 Mutation 的用法。
如果說 Query 是 RESTful 的「查」,那么 Mutation 充當的作用就是「增、刪、改」了。
在 GraphQL 文件夾下創建「Mutation」文件夾,存放和 Mutation 相關的類。
Create Mutation Class
<?php /** * User: yemeishu * Date: 2018/4/3 */namespace App\GraphQL\Mutation;use GraphQL\Type\Definition\Type;use Rebing\GraphQL\Support\Facades\GraphQL;use Rebing\GraphQL\Support\Mutation;use App\User;classNewUserMutationextendsMutation{ ? ?protected $attributes = [ ? ? ? ?'name' => 'NewUser' ? ?]; ? ?public functiontype(){ ? ? ? ?return GraphQL::type('users'); ? ?} ? ?public functionargs(){ ? ? ? ?return [ ? ? ? ? ? ?'name' => [ ? ? ? ? ? ? ? ?'name' => 'name', ? ? ? ? ? ? ? ?'type' => Type::nonNull(Type::string()) ? ? ? ? ? ?], ? ? ? ? ? ?'email' => [ ? ? ? ? ? ? ? ?'name' => 'email', ? ? ? ? ? ? ? ?'type' => Type::nonNull(Type::string()) ? ? ? ? ? ?], ? ? ? ? ? ?'password' => [ ? ? ? ? ? ? ? ?'name' => 'password', ? ? ? ? ? ? ? ?'type' => Type::nonNull(Type::string()) ? ? ? ? ? ?] ? ? ? ?]; ? ?} ? ?public functionresolve($root, $args){ ? ? ? ?$args['password'] = bcrypt($args['password']); ? ? ? ?$user = User::create($args); ? ? ? ?if (!$user) { ? ? ? ? ? ?return null; ? ? ? ?} ? ? ? ?return $user; ? ?}}
Update Mutation Class
<?php /** * User: yemeishu * Date: 2018/4/3 */namespace App\GraphQL\Mutation;use GraphQL\Type\Definition\Type;use Rebing\GraphQL\Support\Facades\GraphQL;use Rebing\GraphQL\Support\Mutation;use App\User;classUpdateUserMutationextendsMutation{ ? ?protected $attributes = [ ? ? ? ?'name' => 'UpdateUser' ? ?]; ? ?public functiontype(){ ? ? ? ?return GraphQL::type('users'); ? ?} ? ?public functionargs(){ ? ? ? ?return [ ? ? ? ? ? ?'id' => [ ? ? ? ? ? ? ? ?'name' => 'id', ? ? ? ? ? ? ? ?'type' => Type::nonNull(Type::int()) ? ? ? ? ? ?], ? ? ? ? ? ?'name' => [ ? ? ? ? ? ? ? ?'name' => 'name', ? ? ? ? ? ? ? ?'type' => Type::nonNull(Type::string()) ? ? ? ? ? ?] ? ? ? ?]; ? ?} ? ?public functionresolve($root, $args){ ? ? ? ?$user = User::find($args['id']); ? ? ? ?if (!$user) { ? ? ? ? ? ?return null; ? ? ? ?} ? ? ? ?$user->name = $args['name']; ? ? ? ?$user->save(); ? ? ? ?return $user; ? ?}}
配置 graphql.php
把 NewUserMutation 和 UpdateUserMutation 加入 graphql mutation 配置中
測試
如上圖,創建兩個 mutation,可以選擇任意一個看運行效果。
創建一個 User:
更新「id: 1」用戶信息:
其中在 graphql-ui 界面,右上角還可以看到「Docs」,點開可以查看這兩個 mutiation 的說明:
總結
通過簡單的「增改查」User 來初步了解 GraphQL 的 Query 和 Mutation 的使用,接下來可以將 GraphQL 作為微服務的「網關」層的前一層來使用。
「未完待續」
coding01 期待您繼續關注