本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
GraphQL 的其他屬性
GraphQL 由幾個設計原則組成,以保持大規模的簡單性和耐用性。
宣告式
GraphQL 是聲明式的,這意味著用戶將通過僅聲明他們想要查詢的字段來描述(塑造)數據。回應只會傳回這些屬性的資料。例如,以下是一項作業,可擷取表格中的
Book
物件,其中 ISBN 13 id
值為 9780199536061:
{ getBook(id: "
9780199536061
") { name year author } }
響應將返回有效負載(name
,和author
)中的字段year
,並且沒有其他內容:
{ "data": { "getBook": { "name": "Anna Karenina", "year": "1878", "author": "Leo Tolstoy", } } }
由於這種設計原則,GraphQL 消除了 REST API 在複雜系統中處理的過度和不足抓取問題。這樣可以更有效率地收集資料並改善網路效能。
階層
GraphQL 具有靈活性,因為請求的數據可以由用戶塑造以適應應用程序的需求。請求的數據始終遵循 GraphQL API 中定義的屬性的類型和語法。例如,下列程式碼片段會顯示新欄位範圍的getBook
作業,quotes
該作業會傳回連結至 Book
9780
199536061 的所有已儲存引號字串和頁面:
{ getBook(id: "
9780199536061
") { name year author quotes { description page } } }
執行此查詢會傳回下列結果:
{ "data": { "getBook": { "name": "Anna Karenina", "year": "1878", "author": "Leo Tolstoy", "quotes": [ { "description": "The highest Petersburg society is essentially one: in it everyone knows everyone else, everyone even visits everyone else.", "page": 135 }, { "description": "Happy families are all alike; every unhappy family is unhappy in its own way.", "page": 1 }, { "description": "To Konstantin, the peasant was simply the chief partner in their common labor.", "page": 251 } ] } } }
正如你所看到的,鏈接到所請求的書的quotes
字段以我們的查詢描述的格式相同的數組返回。儘管此處未顯示,但 GraphQL 具有額外的優點,就是不要特別關注它所擷取的資料位置。 Books
並且quotes
可以單獨存儲,但只要關聯存在,GraphQL 仍然會檢索信息。這意味著您的查詢可以在單個請求中檢索大量的獨立數據。
内省
GraphQL 是自我記錄或內省性。它支持幾個內置操作,允許用戶查看模式中的基礎類型和字段。例如,下面是一個帶有date
和description
字段的Foo
類型:
type Foo { date: String description: String }
我們可以使用該_type
操作來查找模式下的鍵入元數據:
{ __type(name: "Foo") { name # returns the name of the type fields { # returns all fields in the type name # returns the name of each field type { # returns all types for each field name # returns the scalar type } } } }
這將返回一個響應:
{ "__type": { "name": "Foo", # The type name "fields": [ { "name": "date", # The date field "type": { "name": "String" } # The date's type }, { "name": "description", # The description field "type": { "name": "String" } # The description's type }, ] } }
此功能可用於找出特定 GraphQL 結構描述支援的類型和欄位。GraphQL 支援各種各樣的這些內省性作業。如需詳細資訊,請參閱內部檢
強大的打字
GraphQL 通過其類型和字段系統支持強大的打字。當您在模式中定義某些內容時,它必須具有可以在運行時之前驗證的類型。它還必須遵循 GraphQL 的語法規範。這個概念是從其他語言編程沒有什麼不同。例如,以下是較早的Foo
類型:
type Foo { date: String description: String }
我們可以看到,Foo
是將被創建的對象。在的實例中Foo
,會有一個date
和description
字段,這兩個String
原始類型(純量)。在語法上,我們看到這Foo
是聲明的,並且它的領域存在於其範圍內。這種類型檢查和邏輯語法的組合可確保 GraphQL API 簡潔且不言而喻。GraphQL 的類型和語法規範可以在這裡