gpt4 book ai didi

graphql - 如何在 ObjectType 字段注释中使用泛型声明 (nestjs)

转载 作者:行者123 更新时间:2023-12-05 05:57:48 26 4
gpt4 key购买 nike

我需要为我的 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;
}

但这行不通

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

最佳答案

您必须定义一个 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);
}

关于graphql - 如何在 ObjectType 字段注释中使用泛型声明 (nestjs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68713207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com