2023-07-12 06:12:08
GraphQL 是一种用于 API 的查询语言,也是一个用于执行查询的运行时环境。与传统的 RESTful 不同,GraphQL 允许前端精确控制后端返回的数据,减少数据过量获取或不足的问题,并简化接口管理。
数据过量获取或不足
接口数量多,管理复杂
多接口调用导致性能问题
字段修改需前后端协同发布
示例:通过 query 参数定制返回字段:
// 请求query { person(personId:7) { name age }}// 响应{ name: 'lmjben', age: 26}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. 核心类型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: "通过 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"); } } }};创建 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处理业务逻辑并返回数据:
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 服务端,实现高效的数据查询与交互。完整代码参考: