Basically, you can use @Info https://docs.nestjs.com/graphql/resolvers#graphql-argument-decorators decorator from NestJs which is returning an info
parameter from regular apollo resolver.
This decorator injects parsed GraphQL query as AST and allows user to create more complex resolvers.
Working with AST is not straightforward and easy because you need to handle all query types by yourself (fragments, aliases, directives and etc)
But fortunately, there are some libs on the market that make all heavy lifting under the hood.
@jenyus-org/graphql-utils
https://www.npmjs.com/package/@jenyus-org/graphql-utils
This also has pretty useful Decorators for NestJS:
https://www.npmjs.com/package/@jenyus-org/nestjs-graphql-utils
CODE
@Query(() => [PostObject])
async posts(
@FieldMap() fieldMap: FieldMap,
) {
console.log(fieldMap);
}
OUTPUT
{
"posts": {
"id": {},
"title": {},
"body": {},
"author": {
"id": {},
"username": {},
"firstName": {},
"lastName": {}
},
"comments": {
"id": {},
"body": {},
"author": {
"id": {},
"username": {},
"firstName": {},
"lastName": {}
}
}
}
}
graphql-fields-list
https://www.npmjs.com/package/graphql-fields-list
Example in NestJS:
{
post { # post: [Post]
id
author: {
id
firstName
lastName
}
}
}
import { fieldsList, fieldsMap } from 'graphql-fields-list';
import { Query, Info } from '@nestjs/graphql';
@Query(() => [Post])
async post(
@Info() info,
) {
console.log(fieldsList(info)); // [ 'id', 'firstName', 'lastName' ]
console.log(fieldsMap(info)); // { id: false, firstName: false, lastName: false }
console.log(fieldsProjection(info)); // { id: 1, firstName: 1, lastName: 1 };
}
Other similar libs
https://www.npmjs.com/package/graphql-parse-resolve-info
https://github.com/robrichard/graphql-fields