Postgresql GraphQL:在我只选择一列(产品名称)时生成长查询

Postgresql GraphQL:在我只选择一列(产品名称)时生成长查询,postgresql,graphql,apollo,nestjs,typegraphql,Postgresql,Graphql,Apollo,Nestjs,Typegraphql,我将postgres、GraphQL和NestJS与TypeScript和typeORM一起使用 我的GraphQL查询是: { Product { name } } SELECT "ProductEntity"."id" AS "ProductEntity_id", "ProductEntity"."name" AS "ProductEntity_name", "ProductEntity"."description" AS "ProductEntity_de

我将postgres、GraphQL和NestJS与TypeScript和typeORM一起使用

我的GraphQL查询是:

{
   Product { 
    name 
   }
}
SELECT 
 "ProductEntity"."id" AS "ProductEntity_id",
 "ProductEntity"."name" AS "ProductEntity_name",
 "ProductEntity"."description" AS "ProductEntity_description",
 "ProductEntity"."price" AS "ProductEntity_price" 
FROM "product" "ProductEntity"
但在查询日志中,我看到生成的查询是:

{
   Product { 
    name 
   }
}
SELECT 
 "ProductEntity"."id" AS "ProductEntity_id",
 "ProductEntity"."name" AS "ProductEntity_name",
 "ProductEntity"."description" AS "ProductEntity_description",
 "ProductEntity"."price" AS "ProductEntity_price" 
FROM "product" "ProductEntity"
那么为什么不像下面这样呢

SELECT 
     "ProductEntity"."name" AS "ProductEntity_name",
FROM "product" "ProductEntity"
请在下面查找产品解析程序:

@Resolver('product')
export class ProductResolver {
  constructor(private readonly productService: ProductService) {}

  @Query()
  async product() {
    return this.productService.getProducts();
  }

}
产品服务:

@Injectable()
export class ProductService {
  constructor(
    @InjectRepository(ProductEntity)
    private readonly productRepository: Repository<ProductEntity>,
  ) {}


  async getProducts() {
    return await this.productRepository.find();
  }

}

正如Daniel Rearden所说,这更像是您正在使用的ORM的问题。大多数ORM尽可能多地获取信息,除非您告诉他们不要这样做。此外,ORM不知道GraphQL请求询问的是什么信息,因此无法确定要提取哪些字段。相反,ORM提取所有可能的字段并将其映射到一个对象,然后将其传递给GraphQL解析器,GraphQL在其中去除不必要的字段并将响应发送回客户端。这样,无论您要求5个或50个字段,GrpahQL解析器都可以使用它们。您可能会很聪明地阅读需要哪些字段,然后让您的ORM只返回这些字段,但这需要进行大量测试,并充分了解GQL上下文的工作原理。

这个问题将特定于您正在使用的任何ORM以及您在解析器类中如何使用该ORM。大多数ORM,如TypeORM和Sequelize,默认情况下会选择所有可用字段,除非您明确告诉它们要选择哪些字段。@DanielRearden这里是我的解析器@Resolver'product'导出类ProductResolver{constructorprivate readonly productService:productService{}@Query=>[FindProductDto]异步产品{返回this.productService.getProducts;}}从您的评论中我了解到,我是否应该在解析器中为我需要触发的每个查询创建查询函数?请使用代码编辑您的问题-在注释中放置代码块会使代码非常难以阅读。除此之外,我们不知道getProducts是什么或做什么。如果这是续集,则您必须为其提供属性ibutes选项指定要选择的列。@DanielRearden请检查更新的帖子