GraphQL:从兄弟parsing器访问另一个parsing器/字段输出
需要一些帮助。 假设我要求以下数据:
{ parent { obj1 { value1 } obj2 { value2 } } }
我需要在value1parsing器中计算value2的结果。
在价值2中回复承诺的想法,并以某种方式将其置于价值1解决scheme,但如果价值2parsing器没有运行呢?
有什么办法可以做?
我目前的想法是,你可以使用上下文来实现这样的事情。 我可以想象你可以有一个caching像事件发射器混合对象来解决竞争条件问题。
例如,假设我们有一些课
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); } }
然后从你的解决scheme,你可以做这样的事情。
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; } }
我还没有尝试过,但似乎可能对我有用! 如果你给它一个镜头,我很好奇,让我知道它是否工作。 只是为了保留书本,您需要确保实例化“CacheEmitter”类并将其馈送到顶层的GraphQL上下文中。
希望这可以帮助 :)
- Graphql需要模块外部vs GraphQLObjectType内部
- 在GraphQL中将数组作为parameter passing
- 在Nodejs中以GraphQLtypes分配JSON
- GraphQL参数错误:参数types必须是inputtypes,但得到:function GraphQLObjectType(config){
- 如何在GraphQL中插入(Array)字段列表进行变异查询
- 如何为MySQL模型创buildGraphQL模式?
- GraphQL – 传递非特定对象的对象作为参数
- 具有明确错误的GraphQL:Query.example字段types必须是输出types,但得到:
- GraphQL.js Node / Express:如何将对象作为GraphQL查询parameter passing