Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of requested keys in NestJS/GraphQL request

Tags:

graphql

nestjs

I am just fiddling around trying to understand, thus my types are not exact.

@Resolver()
export class ProductsResolver {
    @Query(() => [Product])
    async products() {
        return [{
            id: 55,
            name: 'Moonshine',
            storeSupplies: {
                London: 25,
                Berlin: 0,
                Monaco: 3,
            },
        }];
    }
}

If I request data with query bellow

{
    products{
      id,
      name,
    }
}

I want async carriers() to receive ['id', 'name']. I want to skip getting of storeSupplies as it might be an expensive SQL call.


I am new to GraphQL, I might have missed something obvious, or even whole patterns. Thanks in advance.

like image 879
Akxe Avatar asked Oct 25 '19 01:10

Akxe


1 Answers


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' ]
like image 51
Pooya Haratian Avatar answered Oct 25 '22 13:10

Pooya Haratian