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

问题描述 投票:-1回答:1

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

}

我将Postgres和GraphQL和NestJS与TypeScript和typeORM一起使用我的GraphQL查询是:{产品{名称}}但是在查询日志中,我看到生成的查询是:SELECT“ ...

postgresql graphql apollo nestjs type-graphql
1个回答
0
投票
正如丹尼尔·雷登(Daniel Rearden)所说,这与您正在使用的ORM有关。除非您另行通知,否则大多数ORM都会获取尽可能多的信息。此外,您的ORM并不知道GraphQL请求正在询问什么信息,因此无法确定要拉取的字段。而是,ORM提取所有可能的字段并将它们映射到一个对象,然后将其传递给GraphQL解析器,在这里GraphQL剥离不必要的内容并将响应发送回客户端。这样,无论您要输入5个字段还是50个字段,GrpahQL解析器都可以使用所有这些字段。您可能会聪明地阅读要求的字段,然后让您的ORM只返回那些字段,但这将需要进行大量测试,并对GQL上下文的工作方式有相当的了解。
© www.soinside.com 2019 - 2024. All rights reserved.