When to use `parent` and when to use `root` as first argument in a GraphQL-resolver function

坚强是说给别人听的谎言 提交于 2019-12-11 07:05:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!