GraphQL JavaScript 库 (Node.js):完整指南
GraphQL 是一种 API 查询语言和运行时环境,由 Facebook 开发。在 Node.js 生态系统中,用于处理 GraphQL 的主要库是 graphql 包。它提供了创建、验证和执行 GraphQL 查询所需的所有工具。该库是 Apollo Server、Express-GraphQL 等流行框架的基础。
什么是 GraphQL,为什么需要它?
与 REST API 不同,REST API 的每个端点返回固定的数据结构,而 GraphQL 允许客户端只请求他们需要的字段。这解决了过度获取(获取多余数据)和获取不足(数据不足)的问题。主要优势:
- 查询灵活性:客户端自行决定获取哪些数据。
- 单一入口点:所有查询都发送到一个端点(例如
/graphql)。 - 强类型:GraphQL 模式定义了数据类型及其关系。
- 内省:可以自动生成文档和测试工具(GraphiQL)。
安装 Node.js 的 GraphQL 库
首先,通过 npm 或 yarn 安装该包:
npm install graphql你还需要一个 HTTP 服务器,例如 express,以及中间件 express-graphql(或 Apollo Server)。但 graphql 库本身是核心。
创建第一个模式和解析器
模式是对数据类型和可用操作(查询、变更)的描述。解析器是执行实际数据获取逻辑的函数。
一个包含 User 类型和 user 查询的简单模式示例:
const { graphql, buildSchema } = require('graphql');
// 定义模式const schema = buildSchema(` type User { id: ID! name: String email: String }
type Query { user(id: ID!): User }`);
// 数据(实际项目中为数据库)const users = [ { id: '1', name: '伊万', email: 'ivan@example.com' }, { id: '2', name: '玛丽亚', email: 'maria@example.com' }];
// 解析器const root = { user: ({ id }) => users.find(user => user.id === id)};
// 执行查询graphql({ schema, source: '{ user(id: "1") { name email } }', rootValue: root}).then(response => { console.log(JSON.stringify(response)); // {"data":{"user":{"name":"伊万","email":"ivan@example.com"}}}});GraphQL 中的数据类型
graphql 库支持所有标准标量类型:
String— 字符串;Int— 整数;Float— 浮点数;Boolean— 布尔值;ID— 唯一标识符(序列化为字符串)。
还可以创建自定义对象类型、枚举(enum)、列表([Type])和非空字段(Type!)。
变更和订阅
变更用于修改数据(类似于 REST 中的 POST/PUT/DELETE)。订阅允许通过 WebSocket 实时接收更新。
添加用户的变更示例:
const schema = buildSchema(` type Mutation { addUser(name: String!, email: String!): User }`);
const root = { addUser: ({ name, email }) => { const newUser = { id: String(users.length + 1), name, email }; users.push(newUser); return newUser; }};
// 执行变更graphql({ schema, source: 'mutation { addUser(name: "彼得", email: "petr@example.com") { id name } }', rootValue: root}).then(console.