我试图找出一种干净的方式来处理查询和mongdb投影,所以我不必从数据库中检索过多的信息.假设我有:
// the query
type Query {
getUserByEmail(email: String!): User
}
Run Code Online (Sandbox Code Playgroud)
我有一个User与email和username,让事情变得简单.如果我发送查询而我只想检索电子邮件,我可以执行以下操作:
query { getUserByEmail(email: "test@test.com") { email } }
Run Code Online (Sandbox Code Playgroud)
但在解析器,我的数据库查询检索依然既username和email,但只有其中的一个是由阿波罗服务器查询结果传回.
我只希望数据库检索查询要求的内容:
// 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 */ });
}
Run Code Online (Sandbox Code Playgroud)
当然问题是,获取客户端请求的信息并不是那么简单.
假设我将请求作为上下文传递 - 我考虑使用context.payload(hapi.js),它具有查询字符串,并通过各种.split()s 搜索它,但这感觉有点脏.据我所知,info.fieldASTs[0].selectionSet.selections有字段列表,我可以检查它是否存在.我不确定这是多么可靠.特别是当我开始使用更复杂的查询时.
有更简单的方法吗?
如果您不使用mongDB,则投影是您传递的另一个参数,告诉它明确要检索的内容: …