Skip to content

◈ GraphQL

概述:GraphQL 是由 Facebook 于 2015 年开源的数据查询和操作语言,为 API 提供了灵活高效的替代方案。与传统 REST API 不同,GraphQL 让客户端精确指定所需数据,避免过度获取或获取不足。

概述

GraphQL 属于 数据库 & 领域专用语言 分类。GraphQL 不是一个数据库查询语言(如 SQL),而是一个 API 查询语言——它在客户端和服务器之间定义数据交互契约。

语言特点

  • 按需获取:客户端精确指定需要的字段,不多不少
  • 单一端点:所有查询通过一个 URL 完成,减少请求次数
  • 强类型 Schema:类型系统定义 API 的完整结构
  • 实时订阅:WebSocket 原生支持实时数据推送
  • 自省:可以查询 Schema 本身,自动生成交档和工具

Hello World

graphql
type Query {
  hello: String
}

# Resolver(以 JavaScript 为例)
# const resolvers = {
#   Query: {
#     hello: () => "Hello, World!",
#   },
# };

基础语法

Schema 定义

graphql
# 标量类型
scalar DateTime

# 枚举
enum Role {
  ADMIN
  USER
  GUEST
}

# 对象类型
type User {
  id: ID!
  name: String!
  email: String!
  age: Int
  role: Role!
  posts: [Post!]!
  createdAt: DateTime!
}

type Post {
  id: ID!
  title: String!
  content: String!
  author: User!
  tags: [String!]!
  publishedAt: DateTime
}

# 输入类型(用于 mutation 参数)
input CreateUserInput {
  name: String!
  email: String!
  age: Int
}

# 接口
interface Node {
  id: ID!
}

# 联合类型
union SearchResult = User | Post

查询(Query)

graphql
# 基本查询
query {
  user(id: "1") {
    name
    email
  }
}

# 嵌套查询
query {
  user(id: "1") {
    name
    posts {
      title
      publishedAt
    }
  }
}

# 带变量
query GetUser($userId: ID!) {
  user(id: $userId) {
    name
    email
    posts(limit: 10) {
      title
    }
  }
}

# 多个查询
query {
  user(id: "1") { name }
  allUsers { name email }
}

# 片段(Fragment)
fragment UserFields on User {
  name
  email
  age
}

query {
  user(id: "1") {
    ...UserFields
  }
}

变更(Mutation)

graphql
type Mutation {
  createUser(input: CreateUserInput!): User!
  updateUser(id: ID!, input: UpdateUserInput!): User!
  deleteUser(id: ID!): Boolean!
}

# 调用
mutation CreateUser($input: CreateUserInput!) {
  createUser(input: $input) {
    id
    name
    email
  }
}

订阅(Subscription)

graphql
type Subscription {
  messageAdded(roomId: ID!): Message!
  userStatusChanged(userId: ID!): User!
}

# 订阅实时消息
subscription OnMessageAdded($roomId: ID!) {
  messageAdded(roomId: $roomId) {
    id
    content
    author {
      name
    }
  }
}

指令(Directive)

graphql
query GetUser($withPosts: Boolean!) {
  user(id: "1") {
    name
    posts @include(if: $withPosts) {
      title
    }
    email @skip(if: true)
  }
}

应用领域

  • API 开发:灵活高效的数据查询接口
  • 前端集成:React (Apollo/Relay)、Vue (Vue Apollo) 数据层
  • 微服务网关:多个服务的统一 API 聚合层
  • 移动应用:按需获取数据,减少网络流量
  • 实时应用:WebSocket 订阅实时数据推送
  • 低代码平台:Schema 驱动的自动 UI 生成

开发环境搭建

  1. 后端框架:Apollo Server (Node.js)、Graphene (Python)、Hasura
  2. 前端客户端:Apollo Client、urql、Relay
  3. Schema 设计:GraphQL Editor、Apollo Studio
  4. 测试工具:GraphiQL、Altair、Postman GraphQL
  5. 代码生成:GraphQL Code Generator

学习路线

  1. 入门阶段:Schema 定义 → Query → Mutation → 变量与片段
  2. 进阶阶段:Subscription → 指令 → 分页(Cursor/Offset)→ 错误处理
  3. 实战阶段:Apollo Server → 数据库集成 → 鉴权与授权
  4. 高级阶段:Federation(微服务)→ 性能优化(DataLoader/N+1)→ Schema Stitching

返回首页 | 查看所有语言

编程语言技术文档