技术分享2025年12月29日·5,442

GraphQL API 设计最佳实践

GraphQL 相比 REST API 有哪些优势?如何设计一个高效、可维护的 GraphQL API?

#GraphQL#API#后端

GraphQL API 设计

GraphQL vs REST

GraphQL 的优势

  1. 按需查询:客户端决定返回哪些字段
  2. 单一端点:不需要多个 REST 端点
  3. 强类型:Schema 定义清晰
  4. 避免过度获取/获取不足

Schema 设计

type Query {
  user(id: ID!): User
  posts(limit: Int, offset: Int): [Post!]!
}

type Mutation {
  createPost(input: CreatePostInput!): Post!
  updatePost(id: ID!, input: UpdatePostInput!): Post!
}

type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  content: String!
  author: User!
}

性能优化

DataLoader

解决 N+1 查询问题:

const userLoader = new DataLoader(async (userIds) => {
  const users = await User.find({ _id: { $in: userIds } });
  return userIds.map(id => users.find(user => user.id === id));
});

错误处理

统一的错误格式:

{
  "errors": [{
    "message": "用户不存在",
    "extensions": {
      "code": "USER_NOT_FOUND"
    }
  }]
}
最后更新:2026/1/28