選擇使用REST或GraphQL作為通信模式,需要由業(yè)務(wù)場(chǎng)景決定。GraphQL靈活性也決定了其一定程度上的復(fù)雜性。使用GraphQL也需要考慮在應(yīng)用層面的緩存優(yōu)化,和解決N+1問(wèn)題的批量操作優(yōu)化。
 概述
當(dāng)創(chuàng)建web服務(wù)應(yīng)用程序時(shí),可以選擇使用REST或GraphQL作為通信模式。兩者都可能在HTTP上使用JSON,但有不同的優(yōu)點(diǎn)和缺點(diǎn)。
本文主要比較GraphQL和REST,以操作一個(gè)產(chǎn)品數(shù)據(jù)庫(kù)示例,比較兩種解決方案在執(zhí)行相同的客戶端操作時(shí)的差異:
- 創(chuàng)建處于草稿狀態(tài)的產(chǎn)品
 - 更新產(chǎn)品詳細(xì)信息
 - 獲取產(chǎn)品列表
 - 獲取單個(gè)產(chǎn)品及其訂單的詳細(xì)信息
 
REST
REST(Representational State Transfer,代表性狀態(tài)傳輸)的主要數(shù)據(jù)元素稱為Resource。在本例中,資源是“產(chǎn)品”。
curl --request POST 'http://localhost:8081/product' \
--header 'Content-Type: application/json' \
--data '{
  "name": "Watch",
  "description": "Special Swiss Watch",
  "status": "Draft",
  "currency": "USD",
  "price": null,
  "imageUrls": null,
  "videoUrls": null,
  "stock": null,
  "averageRating": null
}'
curl --request PUT 'http://localhost:8081/product/{product-id}' \
--header 'Content-Type: application/json' \
--data '{
    "name": "Watch",
    "description": "Special Swiss Watch",
    "status": "Draft",
    "currency": "USD",
    "price": 1200.0,
    "imageUrls": [
        "https://graphqlvsrest.com/imageurl/product-id"
    ],
    "videoUrls": [
        "https://graphqlvsrest.com/videourl/product-id"
    ],
    "stock": 10,
    "averageRating": 0.0
}'curl --request GET 'http://localhost:8081/product?size=10&page=0'
{
  "id": 1,
  "name": "T-Shirt",
  "description": "Special beach T-Shirt",
  "status": Published,
  "currency": "USD",
  "price": 30.0,
  "imageUrls": ["https://graphqlvsrest.com/imageurl/1"], 
  "videoUrls": ["https://graphqlvsrest.com/videourl/1"], 
  "stock": 10, 
  "averageRating": 3.5 
}- 通過(guò)訂單獲取單個(gè)產(chǎn)品
 
要獲取產(chǎn)品及其訂單,通常需要先調(diào)用產(chǎn)品列表API,然后調(diào)用訂單資源以查找相關(guān)訂單:
curl --request GET 'localhost:8081/order?product-id=1'
{
  "id": 1,
  "productId": 1,
  "customerId": "de68a771-2fcc-4e6b-a05d-e30a8dd0d756",
  "status": "Delivered",
  "address": "43-F 12th Street",
  "creationDate": "Mon Jan 17 01:00:18 GST 2022"
}除了獲取所有產(chǎn)品的原始操作外,還需要對(duì)每個(gè)感興趣的產(chǎn)品執(zhí)行一次此操作,這會(huì)產(chǎn)生N+1的相關(guān)問(wèn)題。
GraphQL
GraphQL API操作包含Queries和Mutations。Queries負(fù)責(zé)獲取數(shù)據(jù),Mutations用于創(chuàng)建和更新。
Queries和Mutations的Schema模式定義了客戶端可能的請(qǐng)求和響應(yīng)。
curl --request POST 'http://localhost:8081/graphql' \
--header 'Content-Type: application/json' \
--data \
'{
  "query": "mutation {saveProduct (
    product: {
      name: \"Bed-Side Lamp\",
      price: 24.0,
      status: \"Draft\",
      currency: \"USD\"
    }){ id name currency price status}
  }"
}'
{
  "data": {
    "saveProduct": {
      "id": "12",
      "name": "Bed-Side Lamp",
      "currency": "USD",
      "price": 24.0,
      "status": "Draft"
    }
  }
}curl --request POST 'http://localhost:8081/graphql' \
--header 'Content-Type: application/json' \
--data \
'{"query": "mutation {updateProduct(
    id: 11
    product: {
      price: 14.0,
      status: \"Publish\"
    }){ id name currency price status }  
  }","variables":{}}'
{
  "data": {
    "updateProduct": {
      "id": "12",
      "name": "Bed-Side Lamp",
      "currency": "USD",
      "price": 14.0,
      "status": "Published"
    }
  }
}curl --request POST 'http://localhost:8081/graphql' \
--header 'Content-Type: application/json' \
--data \
'{
    "query": "query {products(size:10,page:0){id name status}}"
}'
{
  "data": {
    "products": [
      {
        "id": "1",
        "name": "T-Shirt",
        "status": "Published"
      },
      ...
    ]
  }
}- 通過(guò)訂單獲取單個(gè)產(chǎn)品
 
curl --request POST 'http://localhost:8081/graphql' \
--header 'Content-Type: application/json' \
--data \
'{
    "query": "query {product(id:1){ id name orders{customerId address status creationDate}}}"
}'
{
  "data": {
    "product": {
      "id": "1",
      "name": "T-Shirt",
      "orders": [
        {
          "customerId": "de68a771-2fcc-4e6b-a05d-e30a8dd0d756",
          "status": "Delivered",
          "address": "43-F 12th Street",
          "creationDate": "Mon Jan 17 01:00:18 GST 2022"
        }, 
        ...
      ]
    }
  }
}GraphQL優(yōu)勢(shì)
GraphQL允許靈活和動(dòng)態(tài)的查詢:
- 客戶端只能請(qǐng)求Schema已定義的字段
 - 支持別名用于請(qǐng)求具有自定義鍵值的字段
 - 客戶端可以使用查詢來(lái)管理返回結(jié)果的順序
 - 客戶端可以更好地與API中的任何更改解耦
 
GraphQL傾向于避免昂貴的操作,通??梢允褂肎raphQL在一個(gè)請(qǐng)求中獲取所需的所有數(shù)據(jù)。
何時(shí)使用REST
GraphQL不能替代REST。在以下情況下,可能更適合使用REST:
- 應(yīng)用程序是資源驅(qū)動(dòng)的,其中的操作與各個(gè)資源實(shí)體非常直接和完全地聯(lián)系在一起
 - 需要web緩存,因?yàn)镚raphQL本身并不支持
 - 需要文件上傳,因?yàn)镚raphQL本身并不支持
 
結(jié)論
選擇使用REST或GraphQL作為通信模式,需要由業(yè)務(wù)場(chǎng)景決定。GraphQL靈活性也決定了其一定程度上的復(fù)雜性。
使用GraphQL也需要考慮在應(yīng)用層面的緩存優(yōu)化,和解決N+1問(wèn)題的批量操作優(yōu)化。