GraphQL 是一种用于 API 的查询语言,也是一个满足你数据查询和操作需求的运行时。本文将带你从零开始学习 GraphQL,并通过实际案例展示其在前端应用中的使用。

什么是 GraphQL?

GraphQL 是一种用于 API 的查询语言,也是一个满足你数据查询和操作需求的运行时。GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余。

GraphQL vs REST

与传统的 REST API 相比,GraphQL 具有以下优势:

  • 精确获取数据:客户端可以精确指定需要哪些字段,避免了过度获取或获取不足的问题。
  • 单一端点:GraphQL API 通常只有一个端点,简化了 API 的管理。
  • 强类型系统:GraphQL 有一个强类型系统,可以在编译时发现错误。
  • 实时数据:GraphQL 支持订阅(Subscription),可以实现实时数据更新。

核心概念

Schema

Schema 是 GraphQL API 的核心,它定义了类型系统和可用的 API 操作。

type Query {
  user(id: ID!): User
}

type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  content: String!
  author: User!
}

查询 (Query)

查询用于从服务器获取数据。

query {
  user(id: "1") {
    name
    email
    posts {
      title
      content
    }
  }
}

变更 (Mutation)

变更用于修改服务器上的数据。

mutation {
  createUser(name: "John Doe", email: "john@example.com") {
    id
    name
    email
  }
}

订阅 (Subscription)

订阅用于实时获取数据更新。

subscription {
  postAdded {
    id
    title
    content
  }
}

在前端使用 GraphQL

通过 Apollo Client 来演示如何在前端应用中使用 GraphQL。

安装 Apollo Client

npm install @apollo/client graphql

配置 Apollo Client

import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

const client = new ApolloClient({
  uri: 'http://localhost:4000/graphql',
  cache: new InMemoryCache()
});

执行查询

const GET_USERS = gql`
  query GetUsers {
    users {
      id
      name
      email
    }
  }
`;

client.query({ query: GET_USERS }).then(result => {
  console.log(result.data);
});

执行变更

const ADD_USER = gql`
  mutation AddUser($name: String!, $email: String!) {
    addUser(name: $name, email: $email) {
      id
      name
      email
    }
  }
`;

client.mutate({
  mutation: ADD_USER,
  variables: { name: 'Jane Doe', email: 'jane@example.com' }
}).then(result => {
  console.log(result.data);
});

实践案例

通过一个简单的应用案例来演示 GraphQL 的使用。

// schema.js
const { gql } = require('apollo-server-express');

const typeDefs = gql`
  type Query {
    posts: [Post!]!
  }

  type Mutation {
    addPost(title: String!, content: String!): Post!
  }

  type Post {
    id: ID!
    title: String!
    content: String!
  }
`;

module.exports = typeDefs;
// resolvers.js
const { v4: uuidv4 } = require('uuid');

let posts = [];

const resolvers = {
  Query: {
    posts: () => posts
  },
  Mutation: {
    addPost: (parent, args) => {
      const post = {
        id: uuidv4(),
        title: args.title,
        content: args.content
      };
      posts.push(post);
      return post;
    }
  }
};

module.exports = resolvers;

结论

GraphQL 为现代 Web 应用提供了强大的数据查询能力。通过学习和实践 GraphQL,我们可以构建出更加高效和灵活的前端应用。