1. 程式人生 > 程式設計 >初探 GraphQL

初探 GraphQL

記一次上手graphql的過程,方便以後查閱,文章通篇主要使用javascript寫程式碼,其他語言也同理。

1.安裝

選擇自己需要的語言對應的安裝方式。這裡選擇javascriptApollo Server,因為Apollo Server 支援所有的 Node.js HTTP 伺服器框架:ExpressConnectHAPIKoa。這裡主要使用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 } `; 複製程式碼

解釋:

  1. 首先引入gql,使用了ES6的帶標籤的模板字串語法,是用於檢測是否包含graphql schema語言。
  2. gql後面跟著的是schema語法的字串,其中type Query裡面定義了我們可以查詢的兩個資料launcheslaunch
  3. 先看launches是一個陣列型別,陣列中每一個值都是名為LaunchType的物件型別,type LaunchType定義了該物件的結構,其中,Int、String、Boolean
    是schema語法的基本型別,RocketType又是另一個物件。
  4. 我們回頭再看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; // 同上相同結構的資料,以防上面連結失效
        },}
};
複製程式碼

解釋:

  1. Query的意思是查詢型別,在該物件下的為查詢介面;
  2. launcheslaunch分別對應的介面資料解析器,即方法,方法可帶上引數,第二個引數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
複製程式碼

就能看到以下介面:

image

通過GraphiQL請求:

查詢列表:

左側輸入要請求的資料結構:

query {
	launches {
	    flight_number
        mission_name
        launch_date_local
        launch_success
        rocket {
            rocket_id
            rocket_name
            rocket_type
        }
    }
}
複製程式碼

資料結果:

image

單個查詢:

左側輸入要請求的資料結構和相關引數:

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
}
複製程式碼

資料結果:

image

6.參考

GraphQL 官方入門

apollo-server-express

gql解釋

半路出家老菜鳥 - GraphQL 入門詳解

7.相關程式碼

相關程式碼已上傳GitHub:

hello-graphql