【问题标题】:GraphQL: generate long query while I select only one column (product name)GraphQL:在我只选择一列(产品名称)时生成长查询
【发布时间】:2020-06-06 08:15:03
【问题描述】:

我将 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"

那么为什么不像下面这样呢?

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

}

【问题讨论】:

  • 这个问题将特定于您正在使用的任何 ORM 以及您如何在解析器类中使用该 ORM。大多数 ORM,如 TypeORM 和 Sequelize,默认选择所有可用字段,除非您明确告诉它们要选择哪些字段。
  • @DanielRearden 这是我的解析器 @Resolver('product') export class ProductResolver { constructor(private readonly productService: ProductService) {} @Query(() => [FindProductDto]) async product() { 返回 this.productService.getProducts();我从您的评论中了解到,我应该在解析器中为我需要触发的每个查询创建查询函数吗?
  • 请用代码编辑您的问题——将代码块放入 cmets 会使代码难以阅读。除此之外,我们不知道getProducts 是什么或做什么。如果那是 Sequelize,那么您必须为其提供 attributes 选项来指定要选择的列。
  • @DanielRearden 请查看更新后的帖子

标签: postgresql graphql apollo nestjs typegraphql


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-05-03
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多