apollostack/graphql-server - how to get the fields requested in a query from resolver
2020-Jan answer
The current answer to getting the fields requested in a GraphQL query, is to use the graphql-parse-resolve-info
library for parsing the info
parameter.
The library is "a pretty complete solution and is actually used under the hood by postgraphile", and is recommended going forward by the author of the other top library for parsing the info
field, graphql-fields
.
Use graphql-fields
Apollo server example
const rootSchema = [` type Person { id: String! name: String! email: String! picture: String! type: Int! status: Int! createdAt: Float updatedAt: Float } schema { query: Query mutation: Mutation }`];const rootResolvers = { Query: { users(root, args, context, info) { const topLevelFields = Object.keys(graphqlFields(info)); return fetch(`/api/user?fields=${topLevelFields.join(',')}`); } }};const schema = [...rootSchema];const resolvers = Object.assign({}, rootResolvers);// Create schemaconst executableSchema = makeExecutableSchema({ typeDefs: schema, resolvers,});
Sure you can. This is actually the same functionality that is implemented on join-monster package for SQL based db's. There's a talk by their creator: https://www.youtube.com/watch?v=Y7AdMIuXOgs
Take a look on their info
analysing code to get you started - https://github.com/stems/join-monster/blob/master/src/queryASTToSqlAST.js#L6-L30
Would love to see a projection-monster package for us mongo users :)
UPDATE:There is a package that creates a projection object from info
on npm: https://www.npmjs.com/package/graphql-mongodb-projection