淺淺地談 GraphQL

什麼是 GraphQL?爲何要用 GraphQL?

GraphQL - A Query Language for APIs前端

GraphQL is a new API standard that provides a more efficient, powerful and flexible alternative to REST. It was developed and open-sourced by Facebook and is now maintained by a large community of companies and individuals from all over the world. At its core, GraphQL enables declarative data fetching where a client can specify exactly what data it needs from an API. Instead of multiple endpoints that return fixed data structures, a GraphQL server only exposes a single endpoint and responds with precisely the data a client asked for.express

這是官方關於 GraphQL 的介紹,濃縮成一句話解釋: an API defines how a client can load data from a server後端

大概能夠達到這些優勢:bash

① It lets the client specify exactly what data it needs. / 由前端決定須要哪些資料 ② It uses a type system to describe data. / 資料是具備嚴謹的型態規範 ③ It makes it easier to aggregate data from multiple sources. / 只須要單一的 API 端口架構

GraphQL is the better REST

跟傳統的 REST 的相比,能夠用這張圖解釋:app

根據 REST 的作法,咱們依照每個 Resource 爲單位(一般 depend on 資料庫的表格)。也就是說,前端須要一個資源時即須要呼叫一次 API,N 個資源時須要呼叫 N 次。可能會隱性的增長 Request 與增長新資源的開發成本。 RESTFul 分爲幾個階段:Request → URL Route → Handle Controller -> Multiple Endpointide

在 GraphQL 的架構中將 URL Route → Handle Controller 的動做直接壓縮設計在 API 中透過 Schema 跟 Resolver 取代,將 Resources 視爲是一個 Graph,僅須要透過 One Endpoint API 就能夠作到對資料存取的操做。像這樣使用:工具

爲何要用 GraphQL?

目前應用程式的發展是很快速的,資料的定義也很難在一開始就設定得很完美,很常都是前、後端同時開發同時串接。而由於 API 的興起,一個後端一般須要應付不少前端平臺,像是網頁前、後臺、Android、iOS app 之類的。多個呈現畫面的前端平臺仰賴於一個後端與一個資料庫的來源,RESTFul 實際上是一個相對溫馨的被動解法。反正後端就是開好在那邊,請你們依照文件各取所需就好。可是隨着開發時程拉長、規模變大以後,會發現不一樣的前端可能會有不一樣的要求,此時後端可能就須要一個每一個來源進行調整或是吵架 (?)測試

GraphQL 能夠優雅地處理這個問題,大概有如下幾點好處:fetch

① No more Over and Less - Overfetching and Underfetching / 前端須要什麼本身決定,能夠避免 Response 太肥或不足的問題 ② Benefits of a Schema & Type System / 資料類型的定義可讓達到初步的驗證效果 ③ Rich open-source ecosystem and an amazing community / 開源的社羣資料不少,也有許多有趣的配套解法能夠混搭

Thinking in graphs

前面有提到, GraphQL 將資源視爲一個 Graph,這邊的資源能夠想成是資料庫中的每一種資料。

怎麼開始、怎麼使用

GraphQL 由幾個部分所組成:

  • TypeDefs
  • Resolvers
  • Queries (Query、Mutation)
  • Schema

=> API contain Schema contain Queries contain TypeDefs and Resolvers

TypeDefs

資料能夠定義成下面這樣子,Query 跟 Mutation 做爲 Graph 的 Root,其中在包含 Resource 的組合:

type Query {
  person: person!
  persons: [person]
}
type Mutation {
  create(name: String!, age: Int!): String
}

type Person {
  name: String!
  age: Int!
}
複製代碼

每一種資料均可以設置屬性與類型,能夠看成初步的驗證!

Resolvers

能夠想成一個 Function,負責解析怎樣的需求該對應怎樣的操做。

Queries (Query、Mutation)

Queries 分爲 Query、Mutation 兩種,定義前端的 API 要如何跟後端溝通。

  • Fetching Data with Queries
query {
  Person(last: 1) {
    name
  },
  Persons {
    id
    name
  }
}

# Return:
# {
# "data": {
# "Person": {
# name: "Sarah"
# },
# "Persons": [{
# "id": 1, "name": "Johnny"
# }, {
# "id": 2, "name": "Sarah"
# }]
# }
# }

複製代碼
  • Writing Data with Mutations
mutation {
  create(name: "Bob", age: 36) {
    id
  }
}

# Return:
# {
# "data": {
# "create": {
# "id": 3
# }
# }
# }
複製代碼

Schema

Schema 定義 API 的抽象層,將最上層的 Query Root 往下視爲一個 API Graph。

簡單總結以下:

  • TypeDefs ➞ 定義資料 & Query 的型態
  • Resolvers ➞ 定義操做資料的方式
  • Queries (Query、Mutation) ➞ 資料操做的最上層
  • Schema ➞ 定義 API 的抽象層

實踐第一個 GraphQL Server 開始

目前常見的 GraphQL API Server 大概有如下幾種作法與分別來自不一樣的套件:

  • 第一種寫法:GraphQLObjectType + GraphQLSchema / graphql
  • 第二種寫法:buildSchema + typeDefs + rootValue / graphql
  • 第三種寫法:makeExecutableSchema + typeDefs + resolvers / graphql-tools
  • 第四種寫法:ApolloServer + typeDefs + resolvers / apollo-server
  • 第五種寫法:GraphQLServer + typeDefs + resolvers / graphql-yoga

這邊都是以 Node + Express 爲範例,也先將資料來源假設是靜態變數,實務應用的時候能夠把 Resolver 改成直接存取資料庫的 Function。

第一種寫法:GraphQLObjectType + GraphQLSchema

// 1. 先定義資料來源 & 操做資料的 resolvers
let users = [
  { id: 0, name: 'Tom', sex: 0, },
  { id: 1, name: 'Bob', sex: 0, },
  { id: 2, name: 'Alick', sex: 1, },
];

const userResolver = ({id}) => users.filter(u => u.id == id)[0];
const usersResolver = () => users;

// 2. 利用 GraphQLObjectType 定義 data 的 TypeDefs

const userType = new graphql.GraphQLObjectType({
  name: 'user',
  fields: {
    id: { type: graphql.GraphQLInt },
    name: { type: graphql.GraphQLString },
    sex: { type: graphql.GraphQLInt },
  }
})
const usersType = new graphql.GraphQLList(userType)

// 3. 再利用 GraphQLObjectType 定義 Query 的 TypeDefs 且將 resolvers 定義在其中

const queryType = new graphql.GraphQLObjectType({
  name: 'Query',
  fields: {
    user: {
      type: userType,
      resolve: (_, args) => userResolver(args),
      args: {
        id: { type: graphql.GraphQLInt }
      },
    },
    users: {
      type: usersType,
      resolve: () => usersResolver()
    }
  }
})

// 4. 利用 GraphQLSchema 將 Query 封裝成 Schema

const schema = new graphql.GraphQLSchema({
  query: queryType
});
// 5. 利用 graphqlHTTP 將 Schema 封裝成 API

app.use(
  '/',
  graphqlHTTP({
    schema: schema,
    graphiql: true
  })
);
複製代碼

第二種寫法:buildSchema + typeDefs + rootValue

// 1. 先定義資料來源 & 操做資料的 resolvers
let users = [
  { id: 0, name: 'Tom', sex: 0, },
  { id: 1, name: 'Bob', sex: 0, },
  { id: 2, name: 'Alick', sex: 1, },
];
const userResolver = ({id}) => users.filter(u => u.id == id)[0];
const usersResolver = () => users;

const resolvers = {
  Query: {
    user: (_, args) => userResolver(args),
    users: () => usersResolver()
  },
}

// 2. 利用 template string 定義 data 跟 Query 的 TypeDefs

const typeDefs = `
    type Query {
        user(id: Int!): User
        users: [User]
    },
    type User {
        id: Int
        name: String
        sex: Int
    }
`;

// 3. 利用 buildSchema 將 Query 封裝成 Schema

const schema = graphql.buildSchema(typeDefs);

// 4. 利用 graphqlHTTP + rootValue 將 Query 與 resolver 串接且封裝成 API

app.use(
  '/',
  graphqlHTTP({
    schema: schema,
    rootValue: {
      user: userResolver,
      users: usersResolver
    },
    graphiql: true
  })
);
複製代碼

第三種寫法:makeExecutableSchema + typeDefs + resolvers

// 1. 先定義資料來源 & 操做資料的 resolvers
let users = [
  { id: 0, name: 'Tom', sex: 0, },
  { id: 1, name: 'Bob', sex: 0, },
  { id: 2, name: 'Alick', sex: 1, },
];
const userResolver = ({id}) => users.filter(u => u.id == id)[0];
const usersResolver = () => users;

const resolvers = {
  Query: {
    user: (_, args) => getCourse(args),
    users: () => getCourses()
  },
}

// 2. 利用 template string 定義 data 跟 Query 的 TypeDefs

const typeDefs = `
    type Query {
        user(id: Int!): User
        users: [User]
    },
    type User {
        id: Int
        name: String
        sex: Int
    }
`;

// 3. 利用 makeExecutableSchema 將 Query 跟 resolver 封裝成 Schema

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

// 4. 利用 graphqlHTTP 將 Schema 封裝成 API

app.use(
  '/',
  graphqlHTTP({
    schema: schema,
    graphiql: true
  })
);
複製代碼

第四種寫法:ApolloServer + typeDefs + resolvers

// 1. 先定義資料來源 & 操做資料的 resolvers
let users = [
  { id: 0, name: 'Tom', sex: 0, },
  { id: 1, name: 'Bob', sex: 0, },
  { id: 2, name: 'Alick', sex: 1, },
];
const userResolver = ({id}) => users.filter(u => u.id == id)[0];
const usersResolver = () => users;

const resolvers = {
  Query: {
    course: (_, args) => getCourse(args),
    courses: () => getCourses()
  },
}
// 2. 利用 template string 定義 data 跟 Query 的 TypeDefs

const typeDefs =gql`
    type Query {
        user(id: Int!): User
        users: [User]
    },
    type User {
        id: Int
        name: String
        sex: Int
    }
`;

// 3. 利用 ApolloServer 將 Query 跟 resolver 封裝成 Schema
const server = new ApolloServer({
  typeDefs,
  resolvers,
});

// 4. 利用 applyMiddleware 將 server 做爲 express 的 Middleware API

const app = express();
server.applyMiddleware({ app });
複製代碼

第五種寫法:GraphQLServer + typeDefs + resolvers

// 1. 先定義資料來源 & 操做資料的 resolvers
let users = [
  { id: 0, name: 'Tom', sex: 0, },
  { id: 1, name: 'Bob', sex: 0, },
  { id: 2, name: 'Alick', sex: 1, },
];
const userResolver = ({id}) => users.filter(u => u.id == id)[0];
const usersResolver = () => users;

const resolvers = {
  Query: {
    course: (_, args) => getCourse(args),
    courses: () => getCourses()
  },
}

// 2. 利用 template string 定義 data 跟 Query 的 TypeDefs

const typeDefs = `
    type Query {
        user(id: Int!): User
        users: [User]
    },
    type User {
        id: Int
        name: String
        sex: Int
    }
`;

// 3. 利用 makeExecutableSchema 將 Query 跟 resolver 封裝成 Schema API

const server = new GraphQLServer({
  typeDefs,
  resolvers,
})

server.start()
複製代碼

架構與實現

官方將常見的使用案例分爲三種,也提出三種能夠導入的方式:

① GraphQL server with a connected database ② GraphQL layer that integrates existing systems ③ Hybrid approach with connected database and integration of existing system

GraphQL 也能夠分爲前端與後端:

① A GraphQL server that serves your API. => 套件有: Apollo Client、Relay ② A GraphQL client that connects to your endpoint. => 套件有: express-graphql、 apollo-server、 graphql-yoga

除了先後端以外,也能夠加一些額外的工具:

  • 前端後端間也能夠有一個 Cache Gateway: Apollo Engine
  • 後端與資料庫間也能夠用一個 ORM Layer:Prisma、join-monster

Then ?

GraphQL 的第一步能夠這樣開始:

  1. 規劃資料庫與資料的關係,Thinking in graphs
  2. 配置後端 GraphQL Server + GraphiQL 測試
  3. 開始串前端!

能夠搭配 投影片 閱讀:)

Reference

  1. GraphQL
  2. The Fullstack Tutorial for GraphQL

License

本著做由Chang Wei-Yaun (v123582)製做, 以創用CC 姓名標示-相同方式分享 3.0 Unported受權條款釋出。

相關文章
相關標籤/搜索