Check queried subfields in runtime graphql Nestjs?

Viewed 174

I try to optimize one of my queries which returns @ObjectType() like this:

isFeatureEnabled() {
 .
 .
 .
 return {
   isDistributedInboundEnabled: await getIsDistributedInboundEnabled(),
   isBusinessHoursEnabled: await getIsBusinessHoursEnabled(),
 };
}

However, when executing this query with :

query GetCompany {
  getCompany{
    isFeatureEnabled{
      isBusinessHoursEnabled
      # isDistributedInboundEnabled <--- Do not query this !
    }
  }
}

both of the functions are executed (await getIsDistributedInboundEnabled(), await getIsBusinessHoursEnabled()).

Can I check which subfields are queried in runtime? That way only required functions will be executed on BE.

1 Answers

Ok, personally used approach described in this link and found it working with nest 8.x.x:

Fortunately, we can access the details about the GraphQL query with the @Info() decorator. The most straightforward way to use it is with the graphql-parse-resolve-info library.

import { Info, Query, Resolver } from '@nestjs/graphql';
import { Post } from './models/post.model';
import PostsService from './posts.service';
import { parseResolveInfo, ResolveTree, simplifyParsedResolveInfoFragmentWithType } from 'graphql-parse-resolve-info';
import { GraphQLResolveInfo } from 'graphql';
 
@Resolver(() => Post)
export class PostsResolver {
  constructor(
    private postsService: PostsService
  ) {}
 
  @Query(() => [Post])
  async posts(
    @Info() info: GraphQLResolveInfo
  ) {
    const parsedInfo = parseResolveInfo(info) as ResolveTree;
    const simplifiedInfo = simplifyParsedResolveInfoFragmentWithType(
      parsedInfo,
      info.returnType
    );
 
    const posts = 'author' in simplifiedInfo.fields
      ? await this.postsService.getPostsWithAuthors()
      : await this.postsService.getPosts();
 
    return posts.items;
  }
}
Related