问题
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?
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
}
回答1:
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
}
the resolver signature looks like this:
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.
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.
来源:https://stackoverflow.com/questions/53051712/when-to-use-parent-and-when-to-use-root-as-first-argument-in-a-graphql-resol