简体   繁体   English

GraphQL:从同级解析器访问另一个解析器/字段输出

[英]GraphQL: Accessing another resolver/field output from a sibling resolver

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.我需要 value1 解析器中 value2 的结果进行计算。

Thought of returning a promise in in value2 and somehow take it in value1 resolver, but what if value2 resolver didn't run yet?想过在 value2 中返回一个 promise 并以某种方式在 value1 解析器中接受它,但是如果 value2 解析器还没有运行怎么办?

There`s any way it could be done?有什么办法可以做到吗?

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.只是为了簿记,您需要确保实例化“CacheEmitter”类并将其提供给顶层的 GraphQL 上下文。

Hope this helps :)希望这可以帮助 :)

According to graphql-resolvers : "GraphQL currently does not support a field to depend on the resolved result of another field".根据graphql-resolvers :“GraphQL 目前不支持一个字段依赖于另一个字段的解析结果”。 Using an EventEmiter seems like a very off-spec way of achieving this.使用 EventEmitter 似乎是实现这一目标的一种非常不规范的方式。 graphql-tools offers helper functions that allow you to compose resolvers in a number of ways that should help you. graphql-tools 提供了辅助函数,允许您以多种方式组合解析器,以帮助您。

如果您正在缓存不应造成任何性能问题的内容,您可以再次在 obj1 解析器中加载 obj2 的 value2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM