【问题标题】:Why GraphQL child resolvers do not receive the obj/parent argument?为什么 GraphQL 子解析器不接收 obj/parent 参数?
【发布时间】:2022-01-12 21:51:48
【问题描述】:

我在默认的 GraphQL resolver function' signature 之后编写了一些解析器,可以选择接受四个位置参数:fieldName: (parent, args, context, info) => data;。但是子解析器中完全没有 parent 参数:

...
const resolvers = [
    {
        Query: {
            prop1: (parent, args, context, info) => ({
                childProp1: (args, context, info) => 'Child Property 1',
                childProp2: (args, context, info) => 'Child Property 2',
            }),
        }
    }
]

const server = new ApolloServer(
    {
        typeDefs,
        resolvers,
    }
);

不幸的是,我在 GraphQL 文档中没有找到关于子解析器函数参数的任何参考。所以我想知道如何在子解析器中获取parent 对象的正确方法。

【问题讨论】:

    标签: javascript graphql


    【解决方案1】:

    解析器是其字段被访问的对象的方法,不需要parent 参数,它们被称为方法,它们的this 参数指向对象。

    当你有

    class Value {
        constructor(x) {
            this.property = x;
        }
        methodChild() {
            return this.property;
        }
    }
    const resolvers = {
        Query: {
            prop1: (parent, args, context, info) => new Value('Child Property X'),
        },
        Value: {
            resolverChild: (parent, args, context, info) => parent.property;
        }
    }
    

    然后你可以声明一个

    type Value {
        property: String; # directly accessed as value property
        methodChild: String; # directly invoked as method
        resolverChild: String; # separately resolved
    }
    

    所有三个字段都将产生相同的值。

    【讨论】:

      猜你喜欢
      • 2018-10-21
      • 2020-02-11
      • 2018-07-01
      • 2019-11-06
      • 2019-04-28
      • 2017-02-05
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      相关资源
      最近更新 更多