gpt4 book ai didi

graphql - 突变方法是否需要在顶层?

转载 作者:行者123 更新时间:2023-12-03 19:45:25 26 4
gpt4 key购买 nike

所有文档和教程通常都会显示如下所示的简单突变示例:

extend type Mutation {
edit(postId: String): String
}

但是这样 edit方法必须在所有实体中都是唯一的,对我来说这似乎不是一种非常健壮的写东西方式。我想描述与我们描述查询类似的突变,如下所示:
type PostMutation {
edit(postId: String): String
}

extend type Mutation {
post: PostMutation
}

这似乎是一个有效的模式(它可以编译,我可以看到它反射(reflect)在生成的 graph-i-ql 文档中)。但是我找不到让解析器使用此架构的方法。

这是 GraphQL 支持的案例吗?

最佳答案

这是可能的,但通常不是一个好主意,因为:

它打破了规范。 来自 section 6.3.1 :

Because the resolution of fields other than top‐level mutation fields must always be side effect‐free and idempotent, the execution order must not affect the result, and hence the server has the freedom to execute the field entries in whatever order it deems optimal.



换句话说,只有变异根类型上的字段应该有像 CRUD 操作这样的副作用。

在根上进行突变在概念上是有意义的。 无论您在做什么(喜欢帖子、验证电子邮件、提交订单等),都不依赖于 GraphQL 在采取行动之前必须解析其他字段。这与您实际查询数据时不同。例如,要获得对帖子的评论,我们可能需要解析 user字段,然后是 posts场,最后是 comments每个帖子的字段。在每个“级别”,字段的内容取决于父字段解析为的值。这通常不是突变的情况。

在幕后,突变按顺序解析 .这与并行发生的正常场分辨率相反。例如,这意味着 firstNamelastNameUser类型同时解析。但是,如果您的操作类型是 mutation ,根字段将一次解析一个。所以在这样的查询中:
mutation SomeOperationName {
createUser
editUser
deleteUser
}

每个突变将一次发生一个,按照它们在文档中出现的顺序。但是,这仅适用于 root 并且仅当操作是 mutation 时。 ,所以这三个字段将并行解析:
mutation SomeOperationName {
user {
create
edit
delete
}
}

如果您仍然想这样做,尽管有上述情况,这就是您在使用 makeExecutableSchema 时的做法。 ,这就是 Apollo 在幕后使用的内容:
const resolvers = {
Mutation: {
post: () => ({}), // return an empty object,
},
PostMutation: {
edit: () => editPost(),
},
// Other types here
}

您定义的架构 PostMutation作为对象类型,因此 GraphQL 期望该字段返回一个对象。如果您省略 post 的解析器,它将返回 null,这意味着不会触发返回类型 ( PostMutation ) 的解析器。这也意味着,我们也可以这样写:
mutation {
post
}

它什么都不做,但仍然是一个有效的查询。这是避免这种模式结构的另一个原因。

关于graphql - 突变方法是否需要在顶层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54459947/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com