Matis
Matis

Reputation: 631

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).

Upvotes: 1

Views: 6926

Answers (1)

Michał Lytek
Michał Lytek

Reputation: 12077

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 }

}

Upvotes: 10

Related Questions