初探 GraphQL
阿新 • • 發佈:2019-12-31
記一次上手graphql的過程,方便以後查閱,文章通篇主要使用javascript寫程式碼,其他語言也同理。
1.安裝
選擇自己需要的語言對應的安裝方式。這裡選擇javascript
的Apollo Server
,因為Apollo Server
支援所有的 Node.js HTTP
伺服器框架:Express
、Connect
、HAPI
和 Koa
。這裡主要使用express
。
在專案目錄中執行:
npm install apollo-server-express express
複製程式碼
注:這裡使用的是2.0以上版本,GraphQL官網安裝是1.0版本,所以安裝的不一樣。
2.定義schema
schema
專案中新建schema.js
,寫上以下程式碼:
const { gql } = require('apollo-server-express');
const typeDefs = gql `
type Query {
launches: [LaunchType]
launch(flight_number: Int): LaunchType
}
type LaunchType {
flight_number: Int
mission_name: String
launch_date_local: String
launch_success: Boolean
rocket: RocketType
}
type RocketType {
rocket_id: String
rocket_name: String
rocket_type: String
}
`;
複製程式碼
解釋:
- 首先引入
gql
,使用了ES6的帶標籤的模板字串語法,是用於檢測是否包含graphql schema語言。 -
gql
後面跟著的是schema語法的字串,其中type Query
裡面定義了我們可以查詢的兩個資料launches
和launch
。 - 先看
launches
是一個陣列型別,陣列中每一個值都是名為LaunchType
的物件型別,type LaunchType
定義了該物件的結構,其中,Int、String、Boolean
RocketType
又是另一個物件。 - 我們回頭再看
launch
,不同的是一個物件型別LaunchType
,很好理解,launch
就是單個的意思,對應單個物件而不是陣列。不同的是後面有括號(flight_number: Int)
,這裡是定義了可傳入引數及其型別。
3.定義資料解析
第2步我們定義了schema,我們還需定義其對應的資料直譯器。
在schema.js
中加上:
const resolvers = {
Query: {
launches() {
return axios.get('https://api.spacexdata.com/v3/launches').then(res => res.data);
// return launches; // 同上相同結構的資料,以防上面連結失效
},launch(obj,args) {
return axios.get(`https://api.spacexdata.com/v3/launches/${args.flight_number}`)
.then(res => res.data);
// return launch; // 同上相同結構的資料,以防上面連結失效
},}
};
複製程式碼
解釋:
-
Query
的意思是查詢型別,在該物件下的為查詢介面; -
launches
和launch
分別對應的介面資料解析器,即方法,方法可帶上引數,第二個引數args
是常用的,對應格式定義的一些引數。
4.啟動服務
啟動express服務,並且將appollo服務應用到其中作為中介軟體。
新建index.js
:
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const schema = require('./schema');
const server = new ApolloServer(schema);
const app = express();
// 將apollo服務應用到express服務中作為一箇中介軟體
server.applyMiddleware({ app });
app.listen({ port: 4000 },() =>
console.log(`? Server ready at http://localhost:4000${server.graphqlPath}`)
);
複製程式碼
啟動:
node index.js
複製程式碼
5.除錯
Apollo Server
自帶GraphiQL工具,使除錯graphql介面很方便。
開啟連線:
http://localhost:4000/graphql
複製程式碼
就能看到以下介面:
通過GraphiQL請求:
查詢列表:
左側輸入要請求的資料結構:
query {
launches {
flight_number
mission_name
launch_date_local
launch_success
rocket {
rocket_id
rocket_name
rocket_type
}
}
}
複製程式碼
資料結果:
單個查詢:
左側輸入要請求的資料結構和相關引數:
query ($flightNumber: Int){
launch(flight_number: $flightNumber){
flight_number
mission_name
launch_date_local
launch_success
rocket{
rocket_id
rocket_name
rocket_type
}
}
}
複製程式碼
{
flightNumber": 3
}
複製程式碼
資料結果:
6.參考
7.相關程式碼
相關程式碼已上傳GitHub: