何时使用``parent''以及何时将``root''用作GraphQL-resolver函数中的第一个参数 [英] When to use `parent` and when to use `root` as first argument in a GraphQL-resolver function

查看:121
本文介绍了何时使用``parent''以及何时将``root''用作GraphQL-resolver函数中的第一个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了一些教程和示例,这些教程和示例有时在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
}

推荐答案

此处没有已建立的约定.我已经看到rootparentobj都在不同的参考指南中使用.在一天结束时,您可以随意调用函数参数-您的代码将发挥相同的作用.

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值.此值作为根级字段(即诸如QueryMutation之类的字段)的解析器中的第一个参数传递.通过根目录传递内容的实用性不高-以这种方式传递的任何内容都应该放在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆