Paul Razvan Berg
Paul Razvan Berg

Reputation: 21378

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.

Upvotes: 0

Views: 426

Answers (1)

Paul Razvan Berg
Paul Razvan Berg

Reputation: 21378

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.

Upvotes: 0

Related Questions