Reputation: 51
I need create custom pagination result for my graphql types.
this is my PaginateResult
s @ObjectType
:
@ObjectType()
export class PaginateResult<T> {
@Field()
docs: T[];
@Field()
totalDocs: string;
@Field()
totalPages: string;
}
and its invocation in the 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
s @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 does not work and I get this error:
Error: Undefined type error. Make sure you are providing an explicit type for the "docs" of the "PaginateResult" class.
Upvotes: 5
Views: 2556
Reputation: 141
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);
}
Upvotes: 11