代码之家  ›  专栏  ›  技术社区  ›  robC

子解析器中的GraphQL参数

  •  1
  • robC  · 技术社区  · 8 年前

    我正在使用 graphql-tools 我正在测试一个模式,其中父级和子级都接收一个参数。

    {
      parentWithArg(a: "test") {
        childWithArg(b: "test")
      }
    }
    

    当子解析器运行时,我很困惑,因为第一个参数包含 args ,它与 spec 这个 obj 争论似乎完全没有?

    const resolvers = {
      Query: {
         parentWithArg(obj, args, ctx) {
            console.log('parentWithArg obj:', obj); // `{}` as expected
            return {
                childWithArg(obj, args, ctx) {
                    console.log('childWithArg obj:', obj); // `{ b: 'test' }`
                    return args.b; // null
                }
            };
        },
      },
    };
    

    以下是阿波罗发射台上的示例: https://launchpad.graphql.com/p08j03j8r0

    1 回复  |  直到 8 年前
        1
  •  3
  •   Daniel Rearden    8 年前

    当您为解析器返回的对象中的一个属性返回一个函数时,就会发生这种情况——GraphQL将调用该函数来解析该值,但它只使用三个参数而不是四个参数(args、context和info)来调用它。本例中的父值或“根”值被删除,因为本例中的函数被调用作为解析相同根值的一部分。

    要访问根值,请使用 childWithArg 字段应位于 Parent 键入,如下所示:

    const resolvers = {
      Query: {
         parentWithArg(obj, args, ctx) {
            return {}
        },
      },
      Parent: {
        childWithArg(obj, args, ctx) {
          console.log('childWithArg obj:', obj)
          return args.b
        },
      },
    }