TypeGraphQL使用TypeORM的findAndCount方法

时间:2019-05-10 14:53:51

标签: typescript pagination typeorm type-graphql

我想使用TypeORMfindAndCount函数,该函数返回Promise<[Entity[], number]>进行分页。所以我有一个解析器:

offers(@Arg('page', { defaultValue: 1 }) page: number): Promise<[Offer[], number]> {
    const COUNT = 10
    return this.offerRepository.findAndCount({ take: COUNT, skip: (page - 1) * COUNT })
}

我也正在使用type-graphql,并想像这样用Query注释来注释此解析器:

@Query(returns => ???)

但是我无法弄清楚返回类型,我尝试了一下(由于findAndCount返回的原因,这当然不起作用)

@ObjectType()
class TestType {
    @Field(type => [Offer])
    offers: Offer[]

    @Field()
    count: number
}

并尝试如下使用它:@Query(returns => [TestType])和此@Query(returns => TestType)

1 个答案:

答案 0 :(得分:0)

GraphQL不支持元组,因此您需要创建一个响应对象类型:

@ObjectType()
class OffersResponse {
  @Field(type => [Offer])
  items: Offer[]

  @Field(type => Int)
  totalCount: number
}

然后手动将元组映射到对象:

@Query(returns => OffersResponse)
offers(@Arg('page', { defaultValue: 1 }) page: number): Promise<OffersResponse> {
    const COUNT = 10
    const [items, totalCount] = await this.offerRepository.findAndCount(
      { take: COUNT, skip: (page - 1) * COUNT }
    )
    return { items, totalCount }

}