You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求GraphQL嵌套式Mutation Schema示例及解析器实现方案

实现嵌套分组的GraphQL Mutation Schema

这种把相关Mutation操作分组到专属子对象的模式,能让你的Schema结构更清晰、模块化,非常适合大型项目的维护和扩展。下面是完全符合你需求的完整示例:

完整Schema定义

# 先定义业务所需的输入类型
input UserInput {
  name: String!
  email: String!
}

input PostInput {
  title: String!
  content: String!
  authorId: ID!
}

# 定义基础实体类型
type User {
  id: ID!
  name: String!
  email: String!
}

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

# 按业务模块分组定义Mutation子类型
type UserMutation {
  create(user: UserInput!): User
  delete(id: ID!): Boolean
}

type PostMutation {
  create(post: PostInput!): Post
  delete(id: ID!): Boolean
}

# 根Mutation类型,统一挂载所有分组后的Mutation子对象
type RootMutation {
  user: UserMutation!
  post: PostMutation!
}

# 基础根Query类型(示例结构,可根据业务扩展)
type Query {
  user(id: ID!): User
  post(id: ID!): Post
}

# 最终Schema声明
schema {
  query: Query
  mutation: RootMutation
}

对应的Mutation查询示例

创建用户的Mutation请求

mutation CreateUser($u: UserInput!) {
  user {
    create(user: $u) {
      id
      name
      email
    }
  }
}

删除帖子的Mutation请求

mutation DeletePost($postId: ID!) {
  post {
    delete(id: $postId)
  }
}

批量执行跨分组Mutation的示例

你还可以在同一个请求里执行不同模块的操作:

mutation BatchOperations($u: UserInput!, $postId: ID!) {
  newUser: user {
    create(user: $u) {
      id
      name
    }
  }
  deletedPost: post {
    delete(id: $postId)
  }
}

这种模式的核心优势:

  • 模块划分清晰,用户相关操作都聚合在user节点下,帖子相关操作在post节点下,可读性拉满
  • 扩展性强,新增业务模块时只需添加对应的XXMutation子类型,无需修改根Mutation的原有结构
  • 客户端请求时能更直观地定位到目标操作,降低协作成本

内容的提问来源于stack exchange,提问作者microo8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:25:45