Apollo 服务器:将参数传递给嵌套解析器

Tdy*_*Tdy 7 javascript node.js graphql apollo-server

我的 GraphQL 查询如下所示:

{
    p1: property(someArgs: "some_value") {
        id
        nestedField {
            id
            moreNestedField {
                id
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在服务器端,我使用 Apollo Server。我有一个用于 的解析器,以及用于和property的其他解析器。我需要检索嵌套解析器上的值。我尝试使用解析器上的可用资源来执行此操作:nestedFieldmoreNestedFieldsomeArgscontext

property: (_, {someArgs}, ctx) => {
    ctx.someArgs = someArgs;

    // Do something
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为上下文在所有解析器之间共享,因此如果我property的查询有多个,则上下文值不会很好。

我还尝试在嵌套解析器上使用path可用的。info我可以去现场property,但我在这里没有争论......

我还尝试添加一些数据info,但它没有在嵌套解析器上共享。

在所有解析器上添加参数不是一个选项,因为它会使查询变得非常臃肿并且编写起来很麻烦,我不希望这样。

有什么想法吗?

谢谢!

xad*_*adm 6

可以使用当前返回的值将参数传递给子解析器。稍后将从响应中删除其他数据。

我将“借用”丹尼尔的代码,但没有特定的参数 - 将参数作为参考传递(适合/更干净/更易读,更多参数):

function propertyResolver (parent, args) {
  const property = await getProperty()
  property.propertyArgs = args
  return property
}

// if this level args required in deeper resolvers
function nestedPropertyResolver (parent, args) {
  const nestedProperty = await getNestedProperty()
  nestedProperty.propertyArgs = parent.propertyArgs
  nestedProperty.nestedPropertyArgs = args
  return nestedProperty
}

function moreNestedPropertyResolver (parent) {
  // do something with parent.propertyArgs.someArgs
}
Run Code Online (Sandbox Code Playgroud)

正如丹尼尔斯所说,这种方法的功能有限。您可以chain在子解析器中有条件地得出结果并进行某些操作。您将拥有父级和已过滤的子级...而不是使用子条件过滤的父级(例如在连接表上的 SQL ... WHERE ... AND ... AND ... 中),这可以在父解析器中完成。


cYe*_*Yee 5

不要通过任何来自客户端的参数传递您的参数root,除非IDsparent object,请使用字段级别参数

请在此处检查此答案,了解如何传递参数: /sf/answers/4431009481/

为了简化它,您可以将 args 放入您的字段中:

类型定义示例

服务器定义:

type Query{
  getCar(color: String): Car
  ... other queries
}

type Car{
  door(color: String): Door // <-- added args
  id: ID
  previousOwner(offset: Int, limit: Int): Owner // <-- added args
  ...
}
Run Code Online (Sandbox Code Playgroud)

客户查询:

query getCar(carId:'123'){
  door(color:'grey') // <-- add variable
  id
  previousOwner(offset: 3) // <-- added variable
  ... other queries
}
Run Code Online (Sandbox Code Playgroud)

您应该能够访问子解析器参数中的颜色:

在你的解析器中:

Car{
  door(root,args,context){
   const color = args.color // <-- access your arguments here
  }
  previousOwner(root,args,context){
   const offset = args.offset // <-- access your arguments here
   const limit = args.limit // <-- access your arguments here
  }
  ...others
}
Run Code Online (Sandbox Code Playgroud)

对于你的例子:

会是这样的

{
    p1: property(someArgs: "some_value") { // <-- added variable
        id
        nestedField(someArgs: "some_value") { // <-- added variable
            id
            moreNestedField(offset: 5) {
                id
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)