Get list of requested keys in NestJS/GraphQL request


Basically you can seperate StoreSupplies queries, to make sure not to get them when query on the products.
You can also get the requested keys in your resolver, then query based on them. In order to do that, you can define a parameter decorator like this:

import { createParamDecorator } from '@nestjs/common';

export const Info = createParamDecorator(
  (data, [root, args, ctx, info]) => info,
);

Then use it in your resolver like this:

  @UseGuards(GqlAuthGuard)
  @Query(returns => UserType)
  async getMe(@CurrentUser() user: User, @Info() info): Promise<User> {
    console.log(
      info.fieldNodes[0].selectionSet.selections.map(item => item.name.value),
    );
    return user;
  }

For example, when you run this query

{
  getMe{
    id
    email
    roles
  }
}

The console.log output is:

[ 'id', 'email', 'roles' ]

Another option is to directly use the @Info decorator provided by NestJS, as found here: https://docs.nestjs.com/graphql/resolvers-map#decorators

It could look something like this:

@Resolver()
export class ProductsResolver {
    @Query(() => [Product])
    async products(
    @Info() info
    ) {
        // Method 1 thanks to @pooya-haratian.
        // Update: use this method; read below article to understand why.
        let keys = info.fieldNodes[0].selectionSet.selections.map(item => item.name.value);
        // Method 2 by me, but I'm not sure which method is best.
        // Update: don't use this; read below article to understand why.
        let keys = info.operation.selectionSet.selections[0].selectionSet.selections.map(field => field.name.value);
        return keys;
    }
}

Update: After reading this article on GraphQL Server Basics: Demystifying the info Argument in GraphQL Resolvers, I have learned that fieldNodes is an excerpt of the Abstract Syntax Tree (AST), while operation is the AST of the entire query.

As for why it's safe to select the first object in the array of fieldNodes (fieldNodes[0]), it is because the excerpt starts at the current field, as opposed to the root of the query.

Hence, @pooya-haratian's method was correct. I simply added the elaboration and used NestJS's decorator (@Info).

Tags:

Graphql

Nestjs