【问题标题】:Check queried subfields in runtime graphql Nestjs?检查运行时graphql Nestjs中的查询子字段?
【发布时间】:2022-03-18 15:53:10
【问题描述】:

我尝试优化返回 @ObjectType() 的查询之一:

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

但是,当使用 :

执行此查询时
query GetCompany {
  getCompany{
    isFeatureEnabled{
      isBusinessHoursEnabled
      # isDistributedInboundEnabled <--- Do not query this !
    }
  }
}

这两个函数都被执行了(等待getIsDistributedInboundEnabled(),等待getIsBusinessHoursEnabled())。

我可以检查在运行时查询了哪些子字段吗?这样就只会在 BE 上执行所需的功能。

【问题讨论】:

    标签: graphql nestjs


    【解决方案1】:

    好的,个人使用了这个link 中描述的方法,发现它适用于nest 8.x.x:

    幸运的是,我们可以使用 @Info() 装饰器访问有关 GraphQL 查询的详细信息。最直接的使用方法是使用 graphql-parse-resolve-info 库。

    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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-05
      • 2018-03-31
      • 2019-06-29
      • 2021-09-08
      • 2020-08-15
      • 2022-12-19
      • 2020-05-05
      • 1970-01-01
      • 2021-01-27
      相关资源
      最近更新 更多