使用 Apollo GraphQL Server 撰寫 API(安裝、Query)

Whien
6 min readOct 29, 2019

--

GrapgQL 用過後就回不去了

〉動機

大部分的開發者在學習 SPA(Single Page Application)時,不論從文章或是線上課程,串接資料的方式還是以學習 RESTful 為主,而可能會錯過另一種新嘗試,於是想發起這篇文章,推薦學習時也可以開始嘗試使用 GraphQL

〉閱讀程度

只要十分鐘,誰都能開始開發 GraphQL API

〉目的

主要將繁瑣的 Documentation 內容直接整理成程式碼在文章上,能夠第一時間開始嘗試 GraphQL 開發,不用先看 Documentation 中的冗長說明內容。

〉準備工具

  • Nodejs 開發環境
  • 習慣的編輯器

〉Apollo GraphQL Server

簡介 Apollo GraphQL

目前 GraphQL 社群中貢獻最龐大的組織,主要是因為整合的工具很多,不僅僅只是某一種解決方案,而是嘗試解決各種疑難雜症。

安裝 ApolloServer

> yarn add apollo-server graphql -p
// npm install apollo-server graphql

grapql

基本必須安裝的依賴套件,apollo server 中有些許的 util 工具都會依賴使用。

apollo-server 預設基本配置

  • express server
  • body-parser
  • cors

安裝好後,不再需要手動安裝 body-parsercors 是滿好的,而這兩個配置都會變成透過設定參數的方式來處理。

配置伺服器內容 (index.js)

import { ApolloServer, gql } from 'apollo-server'const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
},
];
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`
const resolvers = {
Query: {
books: () => books
},
};
const server = new ApolloServer({ typeDefs, resolvers })server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`)
})

不要懷疑,就是這麼簡單,短短 30 行就能完成 GraphQL 的基本配置。

啟動伺服器

> node index.js

打開瀏覽器 http://localhost:4000 後將發現會有一個友善的測試環境,並且右邊會有 DOCSSCHEMA 可以看,真的是有夠方便。

圖中因為已經使用 PORT 4000 在另一個環境,因此使用 PORT 4001 不影響文章內容

測試查詢

嘗試開始查詢資料,模擬前端要求,以下查詢語言就是當 SPA 需要請求資料時,給予的查詢內容,GraphQL 中間人就會將這份查詢內容所要求的資料整理並返回

query {
books {
title
author
}
}

〉使用優勢

強迫型別

定義資料規格時,GraphQL 強迫定義資料的型別,型別定義可以幫助未來資料傳輸時,避免意外型別的發生,並且在請求方環境型別會更透明,例如

type Book {
title: String
author: String
}

上述內容表示每一筆 book 資料中,都有 titleauthor 且都要是字串型別

型別錯誤回覆

因為強迫型別的關係,當發生意外的資料回應型別錯誤時,就會立即拋出錯誤,例如將 Book 類型改變一下,再重新請求時,就會出現錯誤

type Book {
title: String
author: Int
}

更語意化

使用 GraphQL 一陣子後,語意化的請求敘述,會讓串接溝通時更加順暢,上述例子中,可以將 books 改為 getBooks

const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
getBooks: [Book]
}
`
const resolvers = {
Query: {
getBooks: () => books
},
};

如此一來,請求時就會更知道預期會獲得什麼結果

開始嘗試了嗎?先一起嘗試到這一步,並試著增加自己需要的資料吧!!

--

--

Whien

遨遊在硬體與軟體世界中,對於計算機一切事物都充滿好奇及熱情。