【问题标题】:how use Generics declaration in ObjectType field annotation (nestjs)如何在 ObjectType 字段注释中使用泛型声明(nestjs)
【发布时间】:2021-10-13 05:09:24
【问题描述】:

我需要为我的 graphql 类型创建自定义分页结果 这是我的 PaginateResult 对象类型

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

  @Field()
  totalDocs: string;

  @Field()
  totalPages: string;
}

并在解析器中调用它

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

和用户对象类型

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

但这不起作用

错误:未定义的类型错误。确保为“PaginateResult”类的“文档”提供显式类型。

【问题讨论】:

    标签: graphql annotations nestjs


    【解决方案1】:

    你必须定义一个 PaginateResult 类型:

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

    使用泛型函数工厂创建专用类型类:

    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) {}
    

    并在解析器中调用它

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

    【讨论】:

      猜你喜欢
      • 2015-11-07
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多