从 REST 到 GraphQL:迁移指南
本文由原文机器翻译。
正在加载文章...
正在加载文章...
本文由原文机器翻译。
随着 Web 应用变得越来越复杂,许多组织正在考虑从 REST API 转向 GraphQL。本综合指南将带你走完迁移过程,重点介绍最佳实践以及需要避免的常见陷阱。
让我们先比较 REST 与 GraphQL 方法之间的根本差异:
| 功能 | REST | GraphQL |
| 端点 | 多个端点 | 单一端点 |
| 数据获取 | 固定响应结构 | 灵活,由客户端指定 |
| 版本控制 | 通常需要 | 持续演进 |
| 网络请求 | 多个请求很常见 | 单个请求即可满足 |
典型 REST API 结构示例:
// REST API Endpoints
GET /api/users/:id
GET /api/users/:id/posts
GET /api/posts
POST /api/posts
PUT /api/posts/:id
// Example REST Controller
class UserController {
async getUser(req, res) {
const user = await User.findById(req.params.id);
const posts = await Post.find({ userId: req.params.id });
res.json({ user, posts });
}
}
将你的 REST 端点转换为 GraphQL schema:
type User {
id: ID!
username: String!
email: String!
posts: [Post!]!
profile: Profile
}
type Post {
id: ID!
title: String!
content: String!
author: User!
comments: [Comment!]!
createdAt: DateTime!
}
type Profile {
bio: String
avatar: String
socialLinks: [SocialLink!]!
}
type Comment {
id: ID!
content: String!
author: User!
}
type Query {
user(id: ID!): User
users(limit: Int, offset: Int): [User!]!
post(id: ID!): Post
posts(
authorId: ID
limit: Int
offset: Int
sortBy: PostSortInput
): [Post!]!
}
type Mutation {
createPost(input: CreatePostInput!): Post!
updatePost(id: ID!, input: UpdatePostInput!): Post!
deletePost(id: ID!): Boolean!
}
使用 DataLoader 进行批处理,创建高效的 resolver:
// DataLoader setup
const userLoader = new DataLoader(async (userIds) => {
const users = await User.find({ _id: { $in: userIds } });
return userIds.map(id => users.find(user => user.id === id));
});
// GraphQL resolvers
const resolvers = {
Query: {
user: async (_, { id }) => userLoader.load(id),
posts: async (_, { limit, offset, authorId }) => {
const query = authorId ? { authorId } : {};
return Post.find(query).skip(offset).limit(limit);
}
},
User: {
posts: async (parent) => {
return Post.find({ authorId: parent.id });
}
},
Post: {
author: async (parent) => userLoader.load(parent.authorId)
}
};
创建一个同时处理 REST 和 GraphQL 请求的网关:
// API Gateway setup
const gateway = express();
// REST endpoints
gateway.use('/api', restRouter);
// GraphQL endpoint
gateway.use('/graphql',
graphqlHTTP({
schema,
graphiql: true,
context: ({ req }) => ({
auth: req.headers.authorization,
loaders: {
user: userLoader,
post: postLoader
}
})
})
);
以下代码演示如何使用中间件在 GraphQL API 中实现身份验证。它会检查请求上下文中是否存在身份验证令牌,验证该令牌,并将用户信息附加到上下文中,以供 resolver 使用。此模式可确保对受保护的 mutation 和 query 进行安全访问:
// GraphQL Authentication middleware
const authenticate = async (resolve, root, args, context, info) => {
if (!context.auth) {
throw new Error('Authentication required');
}
const token = context.auth.split('Bearer ')[1];
const user = await verifyToken(token);
context.user = user;
return resolve(root, args, context, info);
};
// Apply to resolvers
const protectedResolvers = {
Mutation: {
createPost: authenticate(async (_, { input }, context) => {
return Post.create({
...input,
authorId: context.user.id
});
})
}
};
在你的 GraphQL API 中实现全面的错误处理,以便向客户端提供清晰的反馈。以下是一个错误处理实现示例,其中包括自定义错误格式化和结构化错误响应:
// Custom error handling
const formatError = (error) => {
console.error(error);
return {
message: error.message,
code: error.extensions?.code || 'INTERNAL_SERVER_ERROR',
locations: error.locations,
path: error.path,
};
};
// Implementation in schema
const typeDefs = gql`
type Error {
field: String!
message: String!
}
type MutationResponse {
success: Boolean!
errors: [Error!]
data: Post
}
`;
为你的 GraphQL API 实现全面的测试:
describe('GraphQL API Tests', () => {
it('should fetch user with posts', async () => {
const query = `
query GetUser($id: ID!) {
user(id: $id) {
id
username
posts {
id
title
}
}
}
`;
const variables = { id: 'user123' };
const response = await graphql(schema, query, null, {}, variables);
expect(response.data.user).toBeDefined();
});
});
实现查询复杂度分析和速率限制:
const complexityRule = {
Query: {
posts: {
complexity: ({ args, childComplexity }) => {
return (args.limit || 10) * childComplexity;
}
}
}
};
const validateQueryComplexity = (schema, query, variables) => {
const complexity = getQueryComplexity({
schema,
query,
variables,
maximumComplexity: 1000,
complexityRule
});
if (complexity > 1000) {
throw new Error('Query is too complex');
}
};
实现全面的监控:
// Apollo Server monitoring
const server = new ApolloServer({
schema,
plugins: [
ApolloServerPluginUsageReporting({
sendTraces: true,
}),
{
requestDidStart({ request }) {
const startTime = Date.now();
return {
willSendResponse({ response }) {
const duration = Date.now() - startTime;
metrics.recordQueryDuration(duration);
}
};
}
}
]
});
遵循这份详细指南将有助于确保从 REST 到 GraphQL 的平稳过渡,同时保持服务质量和性能。请记住监控迁移的每个阶段,并根据实际反馈和指标调整策略。