iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 4
5
Modern Web

Think in GraphQL系列 第 4

GraphQL 入門: Server Setup X NodeJS X Apollo (寫程式囉!)

img

昨天大致講解完 query 的概念後,很多人一定開始手癢想寫程式了,不然只會用不會做多無聊呢~
今天來介紹如何設定一個 GraphQL Server !

這邊使用最簡單也十分流行的套件 Apollo Server 2 ,幫你 handle 很多雜七雜八的設定。
另外有感於很多程式教學文章不但要安裝東安裝西、新增一堆檔案佔空間每次清理硬碟都不知道拿這堆 tutorial project 怎麼辦...。

因此我將提供兩種 setup 的方式,分別為傳統的 local project setup 或是給那些喜歡雲端化的朋友另一個選項: online project setup 。


Local Project Setup 最完整的開發體驗

1. 安裝

  1. 須先安裝 NodeJS 與 npm,若尚未安裝,可參考此篇:在 Windos, Mac OS X, Linux 安裝 Node.js 網頁應用程式開發環境
  2. 新增一個資料夾 graphql-demo
  3. 進入資料夾並 npm init 設定 project,再來安裝以下兩個套件:
    • apollo-server: Apollo Server 套件,將會提供大部分的功能
    • graphql: Facebook 開發的套件,不會被程式直接引用,但會被其他 GraphQL 套件引用。

或直接輸入以下指令 (for Linux/MacOS):

~ $ mkdir graphql-demo
~/graphql-demo $ cd graphql-demo
~/graphql-demo $ npm init -y
~/graphql-demo $ npm install --save apollo-server graphql

2. 建立 Server

  1. 建立 index.js
~/graphql-demo $ touch index.js
  1. 一個 Apollo Server 由三個部分組成,分別為 Schema Definition 、 Resolver 以及 Web Server。請在 index.js 中輸入:
const { ApolloServer, gql } = require('apollo-server');
// ApolloServer: 讓我們啟動 server 的 class ,不但實作許多 GraphQL 功能也提供 web application 的功能 (背後使用 express)
// gql: template literal tag, 讓你在 Javascript 中使用 GraphQL 語法

// 1. GraphQL Schema 定義
const typeDefs = gql`
  type Query {
    "A simple type for getting started!"
    hello: String
  }
`;

// 2. Resolvers 是一個會對照 Schema 中 field 的 function map ,讓你可以計算並回傳資料給 GraphQL Server
const resolvers = {
  Query: {
    // 需注意名稱一定要對到 Schema 中 field 的名稱
    hello: () => 'world'
  }
};

// 3. 初始化 Web Server ,需傳入 typeDefs (Schema) 與 resolvers (Resolver)
const server = new ApolloServer({
  // Schema 部分
  typeDefs,
  // Resolver 部分
  resolvers
});

// 4. 啟動 Server
server.listen().then(({ url }) => {
  console.log(`? Server ready at ${url}`);
});

PS 若想要用已有的 express server 加入 GraphQL,可參考:Apollo Server: Server Integrations

3. Server 跑起來 !

  1. 執行 index.js
~/graphql-demo $ node index.js
  1. 慣例上,會使用 npm 來執行
    請 Ctrl-C 關掉後修改 package.json 將啟動程序加進 scripts 欄位:
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
+  "start": "node index.js",
},

後執行

~/graphql-demo $ npm start
  1. 打開 http://localhost:4000/,即可看見 GraphQL Playground
    在左側輸入
query {
  hello
}

右側得到回應

{
  "data": {
    "hello": "world"
  }
}

如圖:

  1. 完成!就是這麼簡單!另外如果 NODE_ENV 環境為 production 的話是不會開啟 GraphQL Playground 低 (才不會被看光光)

  2. 如果你跟我一樣懶不喜歡修改完又手動重開,可安裝 nodemon (教學)或直接執行

~/graphql-demo $ npm install --global nodemon

再次修改 package.json 的 scripts 欄位:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start": "node index.js",
+ "dev": "nodemon index.js"
},

後執行

~/graphql-demo $ npm run dev

如此一來每次修改檔案 Server 就會跟著自動重啟囉~

Online Project Setup 雲端愛好者或磁碟空間不夠用的首選

看完上面的 Local Project Setup 是否覺得有些繁複 XD ,還好有 GraphQL Taiwan 社團 上的友人分享,說 Code Sandbox 有提供支援 Apollo Server !!!

只需要三個步驟就可以完成:

  1. 打開 Code Sandbox 並點右上角 Create Sandbox
    https://imgur.com/4PefNoX

  2. 請先登入 Github ,然後直接選取左下方紅色的 Apollo
    https://imgur.com/fYBiD7j

  3. Project 出來後,按左上方的 fork 後就能擁有自己的 project 囉!
    https://imgur.com/yAyW4L3
    裡面就直接包含以上的程式碼,如果有不懂的地方可以回到上方再看看!


如此一來就完成簡單的設定囉!接下來就是分享如何開發自己的 GraphQL Server ,敬請期待!

如果等不及明天的到來,可以到我已經開好的 project:
https://codesandbox.io/s/j1lkoy7nyv

Edit Apollo Server - social network

按下 fork 後就可以自己先玩玩!


上一篇
GraphQL 入門: 基礎 Query X 機制 X HTTP
下一篇
GraphQL 入門:初次實作 Schema 與 Resolver
系列文
Think in GraphQL30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
Zack
iT邦新手 4 級 ‧ 2018-10-19 19:11:32

非常詳細,Codesandbox連Apollo也支持,難怪CodePen越來越少人用。期待下一篇。

我要留言

立即登入留言