[toc]
#### 關于輸入/輸出類型
GraphQL從 Clients 接收數據是通過 字段配制項(fields) 的 參數選項(args) 獲取的。
字段(fields)和參數(args)在定義中都需要類型選項(type),但是fields 和 args 的 type 選項的值是不同的,如GraphQL 的 args在概念上輸入,而 fields 在概念上輸出。
在GraphQL中所有的 types 有兩個類型:input 和 output。
* Output types(or field types)are:Scale,Enum,Object,Interface,Union。
* Input types(or arguments types)are:Scale,Enum,InputObject。
顯然 NonNull 和 List 類型根據它們內部類型屬于上面兩種分類。
輸入復雜類型在 mutations 是相當有價值的,例如 新增/修改一條數據。
#### 輸入對象類型
InputObjectType
GraphQL 為復雜的輸入 定義了 InputObjectType,它的定義和 ObjectType 很相似,除了它的 fields 配制沒有 args 元素 和 resolve 元素 并且它的類型必須是 input type。
Input Object Type 是 GraphQL\Type\Definition\InputObjectType (或其子類)的實例,它的構造函數接收數組配制參數。
#### 配制項
| 名字 | 類型 | 描述 |
| --- | --- | --- |
| name | `string` | `必填` 輸入類型在Schema內的唯一名字 |
| fields | `array` or `callback` returning `array` | `必填` 描述對象字段的數組 (看下面 的詳情) |
| description | `string` | 類型的純文本描述(例如通過GraphQL自動生成文檔) |
每個字段都是下面的條目組成的數組
| 名字 | 類型 | 描述 |
| --- | --- | --- |
| name | `string` | `必填` 輸入字段的名字 如果沒有設置則取數組的鍵名 |
| type | `Type` | `必填` 輸入類型之一的實例 (Scalar, Enum, InputObjectType + 具有 NonNull 和 List修飾的這些類型的組合 |
| description | `string` | 輸入類型的純文本描述(例如通過GraphQL自動生成文檔) |
| defaultValue | `scalar` | 這個輸入類型的默認值 |
#### 示例
~~~
$filters = new InputObjectType([
'name' => 'StoryFiltersInput',
'fields' => [
'author' => [
'type' => Type::id(),
'description' => 'Only show stories with this author id'
],
'popular' => [
'type' => Type::boolean(),
'description' => 'Only show popular stories (liked by several people)'
],
'tags' => [
'type' => Type::listOf(Type::string()),
'description' => 'Only show stories which contain all of those tags'
]
]
]);
~~~
上面的例子我們定義了自己的輸入對象類型,現在我們使用它作為一個字段的參數。
~~~
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'stories' => [
'type' => Type::listOf($storyType),
'args' => [
'filters' => [
'type' => Type::nonNull($filters),
'defaultValue' => [
'popular' => true
]
]
],
'resolve' => function($rootValue, $args) {
return DataSource::filterStories($args['filters']);
}
]
]
]);
~~~
(記住,你可以為具有復雜輸入的字段定義 一個關聯數組的默認值(defaultValue))
然后GraphQL query 可以包含 我們定義的 filters 作為字面值。
~~~
{
stories(filters: {author: "1", popular: false})
}
~~~
或用query variables 的方式作為查詢變量
~~~
query($filters: StoryFiltersInput!) {
stories(filters: $filters)
}
~~~
將包含元素filters的對象 和 query字符串查詢主體一起傳到后臺
~~~
$variables = [
'filters' => [
"author" => "1",
"popular" => false
]
];
~~~
后臺將$variables作為excute的第5個參數,GraphQL將根據您的 InputObjectType定義驗證輸入,并將其傳遞給您的解析器(resolve 或 resolveField)作為參數 $args值的一部分。