GraphQL 简介及其优势
GraphQL 是一种由 Facebook 开发的 API 查询语言。与 REST 中每个端点返回固定数据结构不同,GraphQL 允许客户端仅请求所需的字段。这使得 API 更加灵活和高效。
在本教程中,我们将使用 Apollo Server 库在 Node.js 上创建一个简单的 GraphQL 服务器,配置模式,并实现查询和变更。您将学习:
- 如何安装和配置 Apollo Server
- 如何定义包含数据类型的模式
- 如何为查询和变更编写解析器
- 如何通过 GraphQL Playground 测试 API
您需要 Node.js(版本 16+)和 JavaScript 的基础知识。让我们开始吧!
步骤 1:项目设置和安装依赖项
为项目创建一个新目录并初始化 package.json:
mkdir graphql-tutorialcd graphql-tutorialnpm init -y安装必要的包:
npm install apollo-server graphqlapollo-server 包提供了一个现成的 GraphQL HTTP 服务器,而 graphql 是用于处理模式和查询的核心库。
步骤 2:创建基本模式和解析器
创建文件 index.js 并导入 Apollo Server:
const { ApolloServer, gql } = require('apollo-server');
// 内存数据(模拟数据库)const books = [ { id: '1', title: '战争与和平', author: '列夫·托尔斯泰', year: 1869 }, { id: '2', title: '罪与罚', author: '费奥多尔·陀思妥耶夫斯基', year: 1866 }, { id: '3', title: '大师与玛格丽特', author: '米哈伊尔·布尔加科夫', year: 1967 }];现在使用 gql 标签定义模式:
const typeDefs = gql` type Book { id: ID! title: String! author: String! year: Int }
type Query { books: [Book] book(id: ID!): Book }
type Mutation { addBook(title: String!, author: String!, year: Int): Book }`;创建解析器——为每个查询字段返回数据的函数:
const resolvers = { Query: { books: () => books, book: (parent, args) => books.find(book => book.id === args.id) }, Mutation: { addBook: (parent, args) => { const newBook = { id: String(books.length + 1), title: args.title, author: args.author, year: args.year }; books.push(newBook); return newBook; } }};步骤 3:启动服务器并进行测试
创建服务器实例并启动它:
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => { console.log(`🚀 服务器已就绪,地址:${url}`);});使用命令 node index.js 启动服务器。默认情况下,Apollo Server 在端口 4000 上运行,并打开 GraphQL Playground——一个用于测试查询的交互式环境。
尝试执行一个简单的查询:
query { books { title author }}响应应包含所选字段的书籍数组:
{ "data": { "books": [ { "title": "战争与和平", "author": "列夫·托尔斯泰" }, { "title": "罪与罚", "author": "费奥多尔·陀思妥耶夫斯基" }, { "title": "大师与玛格丽特", "author": "米哈伊尔·布尔加科夫" } ] }}现在测试添加新书的变更:
mutation { addBook(title: "安娜·卡列尼娜", author: "列夫·托尔斯泰", year: 1877) { id title author }}执行变更后,服务器将返回带有分配 ID 的新书对象。