使用buildSchema时如何访问字段解析器中父解析器的值? [英] How to access the value of parent resolver inside a field resolver while using buildSchema?

查看:146
本文介绍了使用buildSchema时如何访问字段解析器中父解析器的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们使用graphqlHTTP时,传递给resolve方法的第一个参数实际上是客户端查询而不是root传递的参数,这对于查询解析器来说很好.但是对于一个需要字段解析器知道父级值的用例,该如何实现呢?

When we are using graphqlHTTP, the first argument passed to the resolve method is actually the parameters passed by the client query not root this is fine for a query resolver. But for a usecase where field resolver needs to know of a value of the parent, how to achieve this?

type Person {
    name: String,
    cityId: String,
    city: City,
}

在上述情况下,我想在哪里city是一个字段解析器,它需要访问cityId,这是父类型的属性.我认为这应该已经作为参数传递给字段解析器,但事实并非如此. 有没有办法做到这一点?

In the above scenario I would like where city would be a field resolver, and it needs access to cityId which is a property on parent type. I assume this should have been passed as parameter to the field resolver but that is not the case. Is there a way to achieve this?

我看到使用对象声明架构时也可以这样做,在这种情况下,传递给解析器函数的firs值为root.

I see same can be done when schema is declared using objects, in that case the firs value passed to resolver functions is root.

推荐答案

简短答案:仅通过根值传递解析函数是有效的,因为它依赖于默认的解析器行为,并且仅适用于根级字段.不幸的是,如果使用buildSchema,提供解析器的唯一方法是通过根值.

Passing resolve functions through the root value only works because it relies on the default resolver behavior, and it only works for root-level fields. Unfortunately, if you use buildSchema, the only way to provide resolvers is through the root value.

您的选择是:

  1. 以编程方式构建架构,而不是使用架构定义语言(SDL).这将允许您为架构中的任何字段指定resolve函数,并且resolve函数将获取所有四个参数(父值,参数,上下文和信息).您可以查看文档以获取一些示例.

  1. Build your schema programatically instead of using Schema Definition Language (SDL). This will allow you to specify a resolve function for any field in your schema, and that resolve function will get all four parameters (parent value, arguments, context and info). You can check out the docs for some examples.

在SDL中编写架构,但使用graphql-tools中的makeExecutableSchema生成GraphQLSchema实例. makeExecutableSchema允许您轻松地为任何字段注入解析器,并提供许多其他功能.可以在这里.

Write your schema in SDL but use makeExecutableSchema from graphql-tools to generate your GraphQLSchema instance. makeExecutableSchema allows you to painlessly inject resolvers for any fields and provides a number of other features. More information about how to generate a schema this way can be found here.

apollo-server转储express-graphql,该引擎在内部使用了makeExecutableSchema,并提供了express-graphql没有的许多其他功能. 检查文档以了解如何入门.

Dump express-graphql for apollo-server, which uses makeExecutableSchema under the hood and provides a number of additional features that express-graphql does not. Check the docs for how to get started.

这篇关于使用buildSchema时如何访问字段解析器中父解析器的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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