GraphQL 零基础教程

GraphQL 零基础教程
最新回答
污界一把手

2023-07-12 06:12:08

GraphQL 零基础教程

GraphQL 是一种用于 API 的查询语言,也是一个用于执行查询的运行时环境。与传统的 RESTful 不同,GraphQL 允许前端精确控制后端返回的数据,减少数据过量获取或不足的问题,并简化接口管理。

GraphQL 的历史背景

  • RESTful 的局限性:传统 RESTful 接口通过约定管理数据交互,但存在以下问题:

    数据过量获取或不足

    接口数量多,管理复杂

    多接口调用导致性能问题

    字段修改需前后端协同发布

  • GraphQL 的优势:通过自定义查询,前端可精确指定所需数据,减少沟通成本,提升开发效率。

示例:通过 query 参数定制返回字段:

// 请求query { person(personId:7) { name age }}// 响应{ name: 'lmjben', age: 26}

GraphQL 核心知识

1. Schema 定义

Schema 是前后端接口的约定,通常写在 .graphql 文件中,包含类型、查询、变更等定义。

示例:定义学生和照片类型

type Student { name: String age: Int sex: Boolean isGood(grade: Int): Boolean}type Photo { url: String size: Int type: PhotoType postedBy: Student}enum PhotoType { SELFLE ACTION}2. 核心类型
  • 内置标量类型:Int、Float、String、Boolean、ID。
  • 自定义类型:如 Student、Photo。
  • 枚举类型:限制字段取值范围(如 PhotoType)。
  • 特殊类型

    Query:定义查询入口,支持嵌套查询。

    Mutation:定义数据修改操作。

    Subscription:实现实时数据推送(基于 WebSocket)。

示例:嵌套查询

query { allPhotos { url postedBy { name } }}3. Resolver 解析器

Resolver 是处理查询逻辑的函数,返回与 Schema 匹配的数据。

示例:解析照片上传者信息

const resolver = { Photo: { postedBy: photo => students.find(item => item.id === photo.postedBy) }};4. 变更(Mutation)

用于修改数据,支持参数传递优化(如 variables 字段)。

示例:上传图片并返回尺寸

mutation postPhoto($input: PostPhotoInput) { postPhoto(url: $input.url) { url size }}// 参数通过 variables 传递// variables: { input: { url: "
https://example.com/image.png"
} }5. 订阅(Subscription)

通过 WebSocket 建立双向通道,实现实时数据推送。

示例:监听新动作照片

subscription { newPhoto(type: "ACTION") { url size }}

Resolver 配置

const resolver = { Mutation: { postPhoto: async (parent, args, { pubsub }) => { pubsub.publish("photo-add", { newPhoto: photo }); } }, Subscription: { newPhoto: { subscribe: (parent, args, { pubsub }) => { return pubsub.asyncIterator("photo-add"); } } }};

GraphQL 小实战:搭建服务端

1. 定义 GraphQL 类型

创建 typeDefs.graphql 文件,定义数据结构:

type Student { name: String age: Int sex: Boolean grade: Int isGood: Boolean}type Photo { url: String size: Int type: PhotoType postedBy: Student}enum PhotoType { SELFLE ACTION}type Query { allStudents(id: Int): [Student] allPhotos: [Photo]}type Mutation { postPhoto(input: PostPhotoInput): Photo}input PostPhotoInput { url: String}type Subscription { newPhoto: Photo}2. 启动 GraphQL 服务

使用 apollo-server-express 快速创建服务:

const express = require("express");const { ApolloServer } = require("apollo-server-express");const fs = require("fs");const typeDefs = fs.readFileSync("./typeDefs.graphql", { encoding: "utf-8" });const server = new ApolloServer({ typeDefs });const app = express();server.applyMiddleware({ app });app.listen({ port: 4000 }, () => { console.log(`Server ready at
http://localhost:4000
${server.graphqlPath}`);});3. 编写 Resolver

处理业务逻辑并返回数据:

const students = [];const photos = [];const resolvers = { Query: { allStudents: () => students, allPhotos: () => photos }, Mutation: { postPhoto: (parent, args) => photos[0] // 简化示例 }, Student: { isGood: parent => parent.grade > 90 }, Photo: { postedBy: photo => students.find(item => item.id === photo.postedBy) }};const server = new ApolloServer({ typeDefs, resolvers });

总结

  • GraphQL 优势:精准数据获取、减少接口数量、支持实时订阅。
  • 核心概念:Schema、类型系统(Query/Mutation/Subscription)、Resolver。
  • 实战步骤:定义类型 → 启动服务 → 编写 Resolver。

通过以上步骤,可快速搭建一个 GraphQL 服务端,实现高效的数据查询与交互。完整代码参考:

lmjben/graphql-demo