Upgrade to Pro — share decks privately, control downloads, hide ads and more …

91APP 電商技術大解密 (2020 線上分享系列):提高前後端串接效率的新作法——使用 GraphQL & React-Apollo

91APP 電商技術大解密 (2020 線上分享系列):提高前後端串接效率的新作法——使用 GraphQL & React-Apollo

主題:提高前後端串接效率的新作法——使用 GraphQL & React-Apollo
講師:周仰皓(Andy Chou)軟體工程師

前後端分離是現今常見的網站架構,然隨著網站的日漸成長、服務的複雜化,提升前端與後端的串接效率將是大型網站無可避免的一項挑戰,本場演講將會分享 91APP 如何運用 GraphQL 及 React-Apollo,幫助團隊解決這項難題。

Youtube: https://youtu.be/0Bb2btvd6Ns

91APP Tech Network: https://www.91app.tech/
91APP Tech Group: https://www.facebook.com/91apptech/

91APP Tech Network

June 11, 2020
Tweet

More Decks by 91APP Tech Network

Other Decks in Programming

Transcript

  1. 大綱 • 以前串接前後端的做法:以 redux-observable 為例 • 什麼是 GraphQL / React

    Apollo? • 為什麼要用 GraphQL / React Apollo? • 簡單實作範例 - 從書籍與作者的陣列,實作資料索取與新增 • 91APP 專案進階範例 - 分類頁無限捲軸 3 建議先備知識:React Hook, Context and JS ES6 syntax
  2. 自我介紹 - 周仰皓 ( Andy Chou ) • 跨電商及電子業的軟體工程師 •

    負責商家官網開發,現使用 React, Redux, NodeJS, GraphQL 等技術。 5
  3. 以前串接前後端的做法 • 早期 - 使用原生 XMLHttpRequest() • JS 推出 Promise

    後 - 使用 Fetch, Axios, SuperAgent 等 • 2013 年 Facebook 首次推出 React 後 - 將 Fetch API 封裝在 React, React-Hooks 內 • 2015 年 Redux 推出 React-Redux, 其他團隊出 Middleware 後 - 將 Fetch API 搭配 Redux-Thunk, Redux-Saga, Redux-Observable 7
  4. 結果... • 程式碼好多好複雜,寫了 111 行 Action - 3 行 Action

    Creator - 29 行 Reducer - 18 行 Epic - 25 行 Fetch API - 11 行 Data Processing - 25 行 9
  5. 什麼是 GraphQL? • 為了詢問 API 而生,新的查詢語言 • 為了滿足查詢語言而生,能與既存資料互動的執行環境 A query

    language for your API GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. https://graphql.org/ 15
  6. 什麼是 React Apollo? • 在 React framework 中,可以讓我們從 GraphQL server

    取資 料(的函式庫) React Apollo allows you to fetch data from your GraphQL server and use it in building complex and reactive UIs using the React framework. https://github.com/apollographql/react-apollo 19
  7. GraphQL 解決的問題 1. 串接後端從多個 Endpoints 變一個 REST API Endpoint domain.com/books

    domain.com/book/:id domain.com/authors domain.com/author/:id GraphQL Endpoint domain.com/graphql?query=xxxx graphQL 自動產生 query string,實作上不必手 動處理 21
  8. React Apollo 解決的問題 處理非同步的複雜邏輯,不需要自己處理 Redux-Observable React Apollo someAction someActionFulfilled someActionRejected

    Redux Store dispatch Epic Middleware Reducer useQuery, useMutation, etcs 自動提供 loading 及 error 兩種變數可取用 自動提供 data 變數可供取用 自動管理 Apollo Client (Context Provider) 24
  9. React Apollo 實作步驟 1. 建立 ApolloClient ( 被封裝後的 React Context

    Provider ) 2. 寫 GraphQL 的類物件專用語法,看要拿甚麼資料就怎麼寫 3. 使用 useQuery, useLazyQuery, useMutation 的 hooks 28
  10. React Apollo - 建立 ApolloClient 1. 用 ApolloClient 物件 定義串接

    GraphQL 的網址 2. 外層新增 <ApolloProvider> 3. 內層 Component 就可使 用 Query 回來的資料 29
  11. 結論 1. GraphQL 可做為 API Gateway,讓前端更方便操作資料 2. React Apollo 可滿足大部分資料操作情境,比如向

    server 取 資料、取更多資料、修改資料 3. 希望可以加速各位開發速度,試用看看吧 37