使用GraphQL构建高效API
💓 博客主页:瑕疵的CSDN主页
📝 Gitee主页:瑕疵的gitee主页
⏩ 文章专栏:《热点资讯》
使用GraphQL构建高效API
- 引言
- GraphQL 简介
- 设置 GraphQL 服务器
- 安装依赖
- 创建 GraphQL 服务器
- 查询操作
- 变更操作
- 实际案例
- 博客应用
- 最佳实践
- 数据验证
- 错误处理
- 性能优化
- 总结
npm install express graphql apollo-server-express
// server.js
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const app = express();
// 定义 GraphQL 模式
const typeDefs = gql`
type Book {
id: ID!
title: String!
author: String!
}
type Query {
books: [Book!]
}
`;
// 定义解析器
const resolvers = {
Query: {
books: () => [
{ id: '1', title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
{ id: '2', title: 'To Kill a Mockingbird', author: 'Harper Lee' },
{ id: '3', title: '1984', author: 'George Orwell' }
]
}
};
// 创建 Apollo 服务器
const server = new ApolloServer({ typeDefs, resolvers });
// 将 Apollo 服务器应用到 Express 应用
server.applyMiddleware({ app, path: '/graphql' });
// 启动服务器
app.listen({ port: 4000 }, () => {
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
});
GraphQL 的查询操作允许客户端精确地指定所需的数据。以下是一个查询书籍列表的示例:
query GetBooks {
books {
id
title
author
}
}
除了查询操作,GraphQL 还支持变更操作,用于修改服务器上的数据。以下是一个添加书籍的示例:
// 修改 resolvers
const resolvers = {
Query: {
books: () => [
{ id: '1', title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
{ id: '2', title: 'To Kill a Mockingbird', author: 'Harper Lee' },
{ id: '3', title: '1984', author: 'George Orwell' }
]
},
Mutation: {
addBook: (_, { title, author }) => {
const book = { id: `${Date.now()}`, title, author };
// 假设这里有一个持久化逻辑
return book;
}
}
};
mutation AddBook {
addBook(title: "Brave New World", author: "Aldous Huxley") {
id
title
author
}
}
假设我们有一个博客应用,需要实现文章的查询和评论的添加功能。以下是实现步骤:
定义数据模型
// schema.js const typeDefs = gql` type Post { id: ID! title: String! content: String! comments: [Comment!] } type Comment { id: ID! text: String! author: String! } type Query { posts: [Post!] } type Mutation { addComment(postId: ID!, text: String!, author: String!): Comment } `;
实现解析器
// resolvers.js const resolvers = { Query: { posts: () => [ { id: '1', title: 'First Post', content: 'This is the first post.', comments: [] }, { id: '2', title: 'Second Post', content: 'This is the second post.', comments: [] } ] }, Mutation: { addComment: (_, { postId, text, author }) => { // 假设这里有一个持久化逻辑 const comment = { id: `${Date.now()}`, text, author }; return comment; } } };
启动服务器
// server.js const express = require('express'); const { ApolloServer, gql } = require('apollo-server-express'); const app = express(); const typeDefs = require('./schema'); const resolvers = require('./resolvers'); const server = new ApolloServer({ typeDefs, resolvers }); server.applyMiddleware({ app, path: '/graphql' }); app.listen({ port: 4000 }, () => { console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`); });
查询和变更操作
query GetPosts { posts { id title content comments { id text author } } } mutation AddComment { addComment(postId: "1", text: "Great post!", author: "John Doe") { id text author } }
GraphQL 可以通过精确的数据获取和减少网络请求次数,显著提升 API 的性能和用户体验。