我正在尝试找出一种简洁的方式来处理查询和 mongdb 投影,这样我就不必从数据库中检索过多的信息。 所以假设我有:
// the query
type Query {
getUserByEmail(email: String!): User
}
我有一个 User
和一个 email
和一个 username
,以保持简单。如果我发送查询并且只想检索电子邮件,我可以执行以下操作:
query { getUserByEmail(email: "test@test.com") { email } }
但在解析器中,我的数据库查询仍然检索 username
和 email
,但只有其中一个被 apollo 服务器作为查询结果传回。
我只希望数据库检索查询要求的内容:
// the resolver
getUserByEmail(root, args, context, info) {
// check what fields the query requested
// create a projection to only request those fields
return db.collection('users').findOne({ email: args.email }, { /* projection */ });
}
当然问题是,获取有关客户请求的信息并不是那么简单。
假设我将请求作为上下文传递 - 我考虑使用具有查询字符串的 context.payload
(hapi.js),并通过各种 .split()
s,但这感觉有点脏。据我所知, info.fieldASTs[0].selectionSet.selections
有字段列表,我可以检查它是否存在。我不确定这有多可靠。尤其是当我开始使用更复杂的查询时。
有没有更简单的方法?
如果您不使用 mongDB,投影是您传入的附加参数,明确告诉它要检索什么:
// telling mongoDB to not retrieve _id
db.collection('users').findOne({ email: 'test@test.com' }, { _id: 0 })
一如既往,感谢这个了不起的社区。p>
最佳答案
2020 年 1 月答案
获取 GraphQL 查询中请求的字段的当前答案是使用 graphql-parse-resolve-info
库来解析 info
参数。
库是“a pretty complete solution and is actually used under the hood by postgraphile”,是 recommended由另一个用于解析 info
字段的顶级库 graphql-fields
的作者继续前进。
关于mongodb - apollostack/graphql-server - 如何从解析器获取查询中请求的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40687045/