1

assume I have schema like this

type Result{ fieldA: TypeA, fieldB: TypeB, # other fileds ... }

fieldB is computed based on fieldA like:

function getData(){...}
function transformData(){...}
resolverA:()=>getData()
resolverB:()=>transformData(getData())

queries could ask for either/both or non of field A/B

assume both getData() and transformData() are expensive operations,

how do I write the resolvers so that :

1) resolverB use the resolved data from resolverA

2) getData only gets called once when both AB fields are in the query

3) None of getData/transformData gets called when only asking for other fields

1 Answer 1

2

I would probably just memoize getData and be done with it. You can use dataloader for that or write your own simple closure that resets it's data on the next tick:

const getData = (function () {
  let cache
  return function () {
    if (cache) return cache
    cache = // do heavy stuff

    process.nextTick(() => {
      cache = null
    })
    return cache
  }
})()
Sign up to request clarification or add additional context in comments.

1 Comment

If we use GraphQLRootContext as cache it will soon contain everything and become dirty. If we don't use GraphQLRootContext as cache, then what should we use?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.