简体   繁体   中英

TypeGraphQL use TypeORM's findAndCount method

I would like to use TypeORM 's findAndCount function which returns Promise<[Entity[], number]> for pagination. So I have a resolver:

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

I'm also using type-graphql and want to annotate this resolver with Query annotation like so:

@Query(returns => ???)

However I can't figure out the return type, I tried this (which of course didn't work, because of what findAndCount returns):

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

    @Field()
    count: number
}

And tried using it like this: @Query(returns => [TestType]) and this @Query(returns => TestType) .

GraphQL doesn't support tuples, so you need to create a response object type:

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

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

And then manually map the tuple to the object:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM