how use Generics declaration in ObjectType field annotation (nestjs)

Viewed 373

i need create custom pagination result for my graphql types this is my PaginateResult ObjectType

@ObjectType()
export class PaginateResult<T> {
  @Field()
  docs: T[];

  @Field()
  totalDocs: string;

  @Field()
  totalPages: string;
}

and call it in resolvers

  @Query((type) => PaginateResult<User>, { nullable: true })
  async getUsers(@Args({ type: () => GetAllUserArgs }) args: GetAllUserArgs) {
    const queryResolver: QueryResolver = new QueryResolver(args);
    return this.userService.getAll(queryResolver.query);
  }

and User ObjectType

@ObjectType()
export class User {
  @Field(() => ID)
  id: string;

  @Field()
  fullName: string;

  @Field()
  companyName: string;

  @Field()
  mobile: string;

  @Field({ nullable: true })
  profilePhoto?: string;

  @Field()
  isActive: boolean;
}

but this not work

Error: Undefined type error. Make sure you are providing an explicit type for the "docs" of the "PaginateResult" class.

1 Answers

You have to define a PaginateResult type:

import { Field, Int, ObjectType } from '@nestjs/graphql';
import { Type } from '@nestjs/common';

export function PaginateResult<T>(ItemType: Type<T>): any {
  @ObjectType({ isAbstract: true })
  abstract class PageClass {
    @Field(() => [ItemType])
    docs: T[];

    @Field(() => Int)
    totalPages: number;
  }

  return PageClass;
}

use the generic function factory to create a dedicated type class:

import { User } from './user.model';
import { ObjectType } from '@nestjs/graphql';
import { Paginated } from 'src/types/paginated-result.type';

@ObjectType()
export class UserPage extends PaginateResult(User) {}

and call it in resolver

  @Query(() => UserPage)
  async getUsers(
    @Args() args: GetAllUserArgs,
  ): Promise<UserPage | HttpException> {
    return this.usersService.getAll(args);
  }
Related