【问题标题】:Getting complete query string from inside of resolver从解析器内部获取完整的查询字符串
【发布时间】:2019-09-15 20:15:34
【问题描述】:

我是 nodejs 和 apollo 服务器的新手,所以不要评判我。

问题听起来与标题完全相同:“如何在解析器函数中获取 graphql 字符串?”。

实际上,每个解析器中都有四个参数:parent、args、context、info。 这里有一些信息:https://www.apollographql.com/docs/apollo-server/essentials/data#type-signature

我下定决心编写函数,该函数在上下文中收集嵌套对象以重新生成查询字符串。为什么我需要它?好问题。我正在编写微服务,所以当我对当前微服务之外的字段进行嵌套查询时,我通过 http 传递查询。

我的解析器:

eventByID: async (root, args, context) => {
const event = await EventModel.findById(root.id);
event.creator = await nestedContextProvider(context, 'creator', event.creator);
return eventFascade(event); //just fascade for object - nothing serious

},

解决嵌套上下文是指nestedContextProvider:

const nestedQueryTraverser = (nestedQueryArray) => {
const nestedQueryTraversed = nestedQueryArray.selectionSet.selections.map(element => (
element.selectionSet === undefined
  ? element.name.value
  : `${element.name.value}{${nestedQueryTraverser(element)}}`));
return nestedQueryTraversed;
};

const nestedContextProvider = async (context, checkField, ID) => {
if (context.operation.selectionSet.selections[0].selectionSet.selections
.find(selector => selector.name.value === checkField)) {
let nestedFieldsArr = context.operation.selectionSet.selections[0]
  .selectionSet.selections.find(selector => selector.name.value === checkField);
nestedFieldsArr = nestedQueryTraverser(nestedFieldsArr);
const a = (await users(ID, nestedFieldsArr));
return a.data.usersByIDs[0];
}
return ID;
};

所以它对我有用,但我知道必须有更好的解决方案。

有什么想法吗?

【问题讨论】:

标签: node.js graphql apollo apollo-server


【解决方案1】:

graphql 包包含一个 print 函数,该函数接受任何 AST 并返回字符串表示,因此您可以执行以下操作:

const { print } = require('graphql')

function anyResolver (parent, args, context, info) {
  const operationString = print(info.operation)
  // Fragments are not included in the operation, but we still need to print
  // them otherwise our document will reference non-existing fragments
  const fragmentsString = Object.keys(info.fragments)
    .map(fragmentName => print(info.fragments[fragmentName]))
    .join('\n\n')
  const documentString = `${operationString}\n\n${fragmentsString}`
}

【讨论】:

  • 太棒了!顺便说一句,有必要承认,如果您在 new ApolloServer 的实例中有上下文指令,那么您将在第三个中拥有 info,但在解析器的第四个 arg 中没有。但是printgraphql 完成了这项工作。谢谢丹尼尔!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-13
  • 2011-02-21
  • 1970-01-01
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
相关资源
最近更新 更多