GraphQL.js 用于 JavaScript (Node.js):完整指南
\n\n1. 这是什么以及为什么需要它?
\n\nGraphQL.js 是 GraphQL 规范在 JavaScript 中的参考实现。它提供了一套完整的工具,用于在服务器端 (Node.js) 和浏览器中创建、执行和验证 GraphQL 查询。与 REST API 中每个端点返回固定数据结构不同,GraphQL 允许客户端精确地只请求其所需的数据,没有多余内容。这解决了过度获取(获取冗余数据)和获取不足(数据不足)的问题,对于移动应用程序和复杂 Web 界面的性能至关重要。
\n\nGraphQL.js 库是 JavaScript 生态系统中所有流行 GraphQL 框架(如 Apollo Server、Express-GraphQL、Yoga 等)的基础。它承担了查询解析、验证、执行解析器以及严格按照规范生成响应的繁重工作。直接使用 GraphQL.js,您可以对查询处理过程拥有最大程度的控制,这在创建自定义中间件、测试工具或与非标准数据源集成时尤其重要。
\n\n使用 GraphQL.js 的主要优势包括:严格的模式类型化、自动生成文档(通过内省查询)、能够在一个查询中高效地合并来自多个来源(数据库、REST API、微服务)的数据,以及内置的错误处理和分页机制。这使得该库成为构建现代、可扩展且灵活的 API 不可或缺的工具。
\n\n2. 安装
\n\n通过 npm(Node 包管理器)安装该库。请确保您已安装 Node.js 12 或更高版本。
\n\nnpm install graphql\n\n要在支持 ES 模块的项目中使用(在 package.json 中设置 type: "module"),请按如下方式导入函数:
\n\nimport { graphql, buildSchema } from 'graphql';\n\n对于 CommonJS(Node.js 中的标准方法):
\n\nconst { graphql, buildSchema } = require('graphql');\n\n3. 快速入门——最小工作示例
\n\n下面是一个最简单的服务器,它接收 GraphQL 查询并返回问候语。此示例演示了库的核心功能:模式定义、解析器和查询执行。
\n\nconst { graphql, buildSchema } = require('graphql');\n\n// 1. 定义模式(模式定义语言 - SDL)\nconst schema = buildSchema(`\n type Query {\n hello: String\n }\n`);\n\n// 2. 定义根解析器(root resolver)\nconst rootValue = {\n hello: () => {\n return 'Hello, GraphQL.js!';\n },\n};\n\n// 3. 执行查询\nconst query = '{ hello }';\n\ngraphql({\n schema,\n source: query,\n rootValue,\n}).then((response) => {\n console.log(JSON.stringify(response, null, 2));\n // 输出:{ "data": { "hello": "Hello, GraphQL.js!" } }\n});\n\n\n4. 主要方法/函数/类
\n\n4.1. buildSchema(schemaString: string): GraphQLSchema
\n功能: 解析用 GraphQL 模式语言 (SDL) 编写的字符串,并创建一个 GraphQLSchema 对象。这是无需使用程序化构造函数即可定义模式的最快方法。
const { buildSchema } = require('graphql');\n\nconst schema = buildSchema(`\n type Query {\n user(id: ID!): User\n }\n type User {\n id: ID\n name: String\n }\n`);\n\n\n4.2. graphql(args: GraphQLArgs): Promise<GraphQLResult>
\n功能: 执行 GraphQL 查询的主要函数。