何时使用``parent''以及何时将``root''用作GraphQL-resolver函数中的第一个参数 [英] When to use `parent` and when to use `root` as first argument in a GraphQL-resolver function
问题描述
我已经看到了一些教程和示例,这些教程和示例有时在graphql解析器中使用parent
,有时将root
作为其第一个参数.
I've seen some tutorials and examples out there who are sometimes using parent
and sometimes using root
for their first argument in a graphql resolver.
在哪种情况下,正确的命名是什么?为什么?
What would be the correct naming in which situation and why?
例如(nodejs):
For example(nodejs):
signup: (root, args, context, info) => signup(root, args, context, info)
vs
signup: (parent, args, context, info) => signup(parent, args, context, info)
或在执行注册的功能中:
or in the function which does the signup:
const signup(root, args, context, info) = {
// do magic stuff
}
vs
const signup(parent, args, context, info) = {
// do magic stuff
}
推荐答案
此处没有已建立的约定.我已经看到root
,parent
和obj
都在不同的参考指南中使用.在一天结束时,您可以随意调用函数参数-您的代码将发挥相同的作用.
There's not an established convention here. I've seen root
, parent
, and obj
all used in different reference guides. At the end of the day you can call your function arguments whatever you want -- your code will function the same.
也就是说,我通常使用字段要部分解析的类型的名称.所以对于类似
That said, I typically use the name of the type that field being resolved in part of. So for a type like
type RoomRental {
user: User
date: Date
}
解析器签名如下:
user: (roomRental, args, context, info) => {
//
}
我发现,这使您(或队友)阅读代码时更容易推断出解析器的工作方式.同样,这只是我的偏爱,但是您可能会发现它有助于使您的代码更易消化.
I find that this makes it easier to reason about what your resolver is doing when you (or a teammate) are reading the code. Again, this is just my preference, but you may find it helps make your code a little more digestible.
为完成操作,我还要补充一点GraphQL.js确实具有可配置的root
值.此值作为根级字段(即诸如Query
或Mutation
之类的字段)的解析器中的第一个参数传递.通过根目录传递内容的实用性不高-以这种方式传递的任何内容都应该放在context
中.但是,root
值是实现的一部分,并且可能是为什么您看到很多示例使用root
作为第一个参数的名称的原因.
For completion, I'd also add that GraphQL.js does have a configurable root
value. This value is passed down as the first argument in the resolvers of root-level fields (that is, fields on types like Query
or Mutation
). There's not much utility in passing things through the root -- anything you might pass in that way should probably go in your context
instead. However, the root
value is part of the implementation, and may be why you see a lot of examples use root
as the name for that first argument.
这篇关于何时使用``parent''以及何时将``root''用作GraphQL-resolver函数中的第一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!