GraphQL: Accessing another resolver/field output from a sibling resolver

微笑、不失礼 提交于 2019-12-05 21:36:44

问题


need some help. Let say Im requesting the following data:

{
  parent {
    obj1    {
        value1
    }
    obj2    {
        value2
    }
  }
}

And I need the result of value2 in value1 resolver for calculation.

Thought of returning a promise in in value2 and somehow take it in value1 resolver, but what if value2 resolver didn’t run yet?

There`s any way it could be done?


回答1:


My immediate thought is that you could use the context to achieve something like this. I'd imagine you could have a cache like object mixed with an event emitter to solve the race condition issue.

For example, assume we had some class

class CacheEmitter extends EventEmitter {

  constructor() {
    super();
    this.cache = {};
  }

  get(key) {
    return new Promise((resolve, reject) => {
      // If value2 resolver already ran.
      if (this.cache[key]) {
        return resolve(this.cache[key]);
      }
      // If value2 resolver has not already run.
      this.on(key, (val) => {
        resolve(val);
      });
    })
  }

  put(key, value) {
    this.cache[key] = value;
    this.emit(key, value);
  }
}

Then from your resolvers you could do something like this.

value1Resolver: (parent, args, context, info) => {
  return context.cacheEmitter.get('value2').then(val2 => {
    doSomethingWithValue2();
  });
}

value2Resolver: (parent, args, context, info) => {
  return doSomethingToFetch().then(val => {
    context.cacheEmitter.put('value2', val);
    return val;
  }
}

I haven't tried it but that seems like it may work to me! If you give it a shot, I'm curious so let me know if it works. Just for book keeping you would need to make sure you instantiate the 'CacheEmitter' class and feed it into the GraphQL context at the top level.

Hope this helps :)




回答2:


According to graphql-resolvers: "GraphQL currently does not support a field to depend on the resolved result of another field". Using an EventEmiter seems like a very off-spec way of achieving this. graphql-tools offers helper functions that allow you to compose resolvers in a number of ways that should help you.



来源:https://stackoverflow.com/questions/41597148/graphql-accessing-another-resolver-field-output-from-a-sibling-resolver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!