GraphQL 漸進學習 01-GraphQL-快速上手

01-GraphQL-快速上手

目標

  • 建立一個 Node Express GraphQL server
  • 採用可視化 GraphiQL IDE 進行測試

代碼

建立一個 node 項目

mkdir graphql-example
cd graphql-example
npm init

安裝依賴包

npm install --save apollo-server-express graphql-tools graphql express body-parser

運行官方示例

爲了突出關鍵點,省略完整代碼

完整代碼移步 quick-start.jshtml

1 建立文件 quick-start.js

vi quick-start.js

2 定義數據結構

// GraphQL schema
const typeDefs = `
  type Query { books: [Book] }
  type Book { title: String, author: String }
`

3 定義處理函數

// resolvers
const resolvers = {
  Query: {books: () => books}
}

4 合併定義

const schema = makeExecutableSchema({
  typeDefs,
  resolvers
})

5 路由 GraphQL 數據服務

app.use('/graphql', bodyParser.json(), graphqlExpress({schema}))

6 路由 GraphIQL IDE

app.use('/graphiql', graphiqlExpress({endpointURL: '/graphql'}))

運行

啓動服務

node quick-start.js

npm script

運行 GraphiQL IDE 編輯器

輸入網址 http://localhost:3000/graphiql

GraphiQL IDE

你能夠試着改變查詢條件
{
  books {
    title
    author
  }
}

與服務器通信

抓包看看

GraphQL Request

  • URL 是代碼中定義的路由 Request URL: http://localhost:3000/graphql?
  • GraphiQL IDE 默認用 POST 方式
  • 請求數據體
{
  "query": "{\n  books {\n    title\n    author\n  }\n}\n",
  "variables": null,
  "operationName": null
}
query 查詢體
variables 參數
operationName 操做名稱

參考

相關文章
相關標籤/搜索