Search code examples
graphqlapolloreact-apolloapollo-client

How to dynamically reuse resolvers in Apollo?


Say I have the following query:

// queries.js

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

And the following resolvers:

// resolvers.js

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

root.baz is undefined.

Is it possible to reuse baz in computing qux? I couldn't find a solution for this in the docs.


Solution

  • I figured it out.

    Here are all the params passed to a resolver:

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

    We can use the context to pass data between resolvers:

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

    Also see the docs on local state.