apollostack/graphql-server - how to get the fields requested in a query from resolver
<p>I am trying to figure out a clean way to work with queries and mongdb projections so I don't have to retrieve excessive information from the database. 
So assuming I have:</p>

<pre><code>// the query
type Query {
  getUserByEmail(email: String!): User
}
</code></pre>

<p>And I have a <code>User</code> with an <code>email</code> and a <code>username</code>, to keep things simple. If I send a query and I only want to retrieve the email, I can do the following:</p>

<pre><code>query { getUserByEmail(email: "test@test.com") { email } }
</code></pre>

<p>But in the resolver, my DB query still retrieves both <code>username</code> and <code>email</code>, but only one of those is passed back by apollo server as the query result. </p>

<p>I only want the DB to retrieve what the query asks for:</p>

<pre><code>// 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 */ });
}
</code></pre>

<p>Of course the problem is, getting information on what the client is requesting isn't so straightforward.</p>

<p>Assuming I pass in request as context - I considered using <code>context.payload</code> (hapi.js), which has the query string, and searching it through various <code>.split()</code>s, but that feels kind of dirty. As far as I can tell, <code>info.fieldASTs[0].selectionSet.selections</code> has the list of fields, and I could check for it's existence in there. I'm not sure how reliable this is. Especially when I start using more complex queries.</p>

<p>Is there a simpler way?</p>

<p>In case you don't use mongDB, a projection is an additional argument you pass in telling it explicitly what to retrieve:</p>

<pre><code>// telling mongoDB to not retrieve _id
db.collection('users').findOne({ email: 'test@test.com' }, { _id: 0 })
</code></pre>

<p>As always, thanks to the amazing community.</p>