如何在 Apollo 中动态重用解析器?

How to dynamically reuse resolvers in Apollo?

假设我有以下查询:

// queries.js

const GET_FOO = gql`
  query Foo {
    foo {
      id
      bar
      baz @client
      qux @client
    }
  }
`

以及以下解析器:

// resolvers.js

export default {
  Foo: {
    baz: root => computeBaz(),
    qux: root => computeQux(root.baz),
  }
}

root.baz 未定义。

是否可以在计算 qux 时重用 baz?我在文档中找不到解决方案。

我想通了。

以下是传递给解析器的所有参数:

fieldName: (obj, args, context, info) => result;

我们可以使用上下文在解析器之间传递数据:

export default {
  Foo: {
    baz: (root, _args, context) => {
      context.baz = computeBaz()
      return context.baz;
    },
    qux: (root, _args, context) => {
      return computeQux(context.baz);
    }
  }
}

另请参阅本地状态的 docs