Skip to main content

學習 GraphQL 筆記(三)Resolver

Updated Markdown
Part of seriesGraphQL

前面學完了怎麼請求資料,怎麼定義 Schema,最後我們就是要來學習怎麼解析請求來拿取資料。

此處我是搭配 Apollo 來使用,所以可能跟其他 Framework 不同。到了 Resolver 基本上我認為就已經不關 GraphQL 的事情了,就主要是後端的邏輯該怎麼利用得到的參數來從 Database 取得資料或更新資料。

Operation

前面提到 GraphQL 的 Operation 是 Entry Point,所以 Front End 請求所用的都需要在 Resolver 也定義,注意名稱要一樣,才能 Mapping 起來。

# Schema

type Person {
  name: String
  age: Int

}

type Cat {
  name: String
  weight: Float
  height: Float
  master: Person

}

# Query
{
  cat {
    name
    weight
    height
    master

  }

}

按照上面的設定 Resolver 的話就要如下面的範例編寫:

{

  Query: {
    cat: (parent, args, context, info) => {
      // 在此處編寫從資料庫拿取資料的 function

      return {
         name: "Hino",
         weight: 4.5,
         height: 50

       };

    }

  }
  Person: (parent, args, context, info) {
    return {
      name: "Rukeith",
      age: 18

    };

  }

}
  • parent:當前上一個 Resolver 的回傳值

  • args:傳入的參數

  • context:在 Resolver 解析鏈中不斷傳遞的中間變數

  • info:當前 Query 的 AST 物件

parent 會是上一個 Resolver 的回傳值,所以 cat要求了 master 欄位。而其 master 的 Object Type 是 Person。所以跑完 cat ,會往下 Mapping 到 Person 的 Resolver。此時 Person 的 parent 的值就會是

{
  name: "Hino",
  weight: 4.5,
  height: 50

}

如果在 master 傳入參數,如 master(limit: 1) 。 Person 的 Resolver 參數 args 就會是:

{
  limit: 1

}

缺陷

目前看到的是 GraphQL 應該只有一個 Entry Point 所以,沒辦法適用於過往 HTTP 的 Cache 機制,和在中間層做 Authorize 的部分。我也還沒看到有在介紹這塊的文章,希望有推薦的可以跟我說一下,感謝大家的觀看。

Reference

  1. https://www.apollographql.com/

  2. https://graphql.org

  3. https://graphql.cn

  4. https://blog.apollographql.com/the-anatomy-of-a-graphql-query-6dffa9e9e747

  5. https://juejin.im/post/5b03cdcd51882542c760eaef

  6. https://blog.apollographql.com/graphql-explained-5844742f195e

About the author

  • I am not a programmer just a leaner. Writing JavaScript, Python, and Go and doing something on Kubernetes.

No comments yet. Be the first to comment.

More from this blog