Type-GraphQL 将分页对象添加到解析器
Type-GraphQL adding pagination object to resolver
我创建了一个使用 TypeORM 搜索公司对象的 GraphQL 解析器,我希望允许客户端(可选)使用分页或排序对象进行查询,所以我编写了这个解析器:
@ArgsType()
class CompanyProductArgs {
@Field()
OrderBy?: {
fieldName: string;
direction: DirectionEnum;
};
@Field()
Pagination?: {
take: number;
skip: number;
};
}
@Resolver()
export class CompanyProductResolver {
@Query(() => [CompanyProduct])
companyProducts(@Args() { OrderBy, Pagination }: CompanyProductArgs) {
let args = {};
if (OrderBy) {
args = {
...args,
order: {
[OrderBy.fieldName]: OrderBy.direction,
},
};
}
if (Pagination) {
args = {
...args,
skip: Pagination.skip,
take: Pagination.take,
};
}
return CompanyProduct.find(args);
}
}
但是运行这个returns:
Error: You need to provide explicit type for CompanyProductArgs#OrderBy
解决这个问题的方法是使用自定义缩放器(我认为),但是 type-GraphQL documentation 只提供了一个例子,其中只有一个变量被接受,但我想接受一个对象使用 2 个键(在本例中为 take 和 skip)。我将如何编写一个接受对象的调用程序,例如这样的分页对象:
{
take: 10
skip: 5
}
ArgsType
装饰器在 Args
(Source) 中注入后将所有内容展平。我建议像这样使用 InputType
装饰器:
@InputType()
class OrderByInputType {
@Field()
fieldName: string;
@Field()
direction: DirectionEnum;
}
@InputType()
class PaginationInputType {
@Field(() => Int)
take: number;
@Field(() => Int)
skip: number;
}
然后将它们作为可选参数传递,如下所示:
companyProducts(
@Arg("OrderBy", { nullable: true }) OrderBy?: OrderByInputType,
@Arg("Pagination", { nullable: true }) Pagination?: PaginationInputType
)
您可能会以更简洁或更紧凑的方式执行此操作,但这应该可行,您可以从这里开始尝试!
我创建了一个使用 TypeORM 搜索公司对象的 GraphQL 解析器,我希望允许客户端(可选)使用分页或排序对象进行查询,所以我编写了这个解析器:
@ArgsType()
class CompanyProductArgs {
@Field()
OrderBy?: {
fieldName: string;
direction: DirectionEnum;
};
@Field()
Pagination?: {
take: number;
skip: number;
};
}
@Resolver()
export class CompanyProductResolver {
@Query(() => [CompanyProduct])
companyProducts(@Args() { OrderBy, Pagination }: CompanyProductArgs) {
let args = {};
if (OrderBy) {
args = {
...args,
order: {
[OrderBy.fieldName]: OrderBy.direction,
},
};
}
if (Pagination) {
args = {
...args,
skip: Pagination.skip,
take: Pagination.take,
};
}
return CompanyProduct.find(args);
}
}
但是运行这个returns:
Error: You need to provide explicit type for CompanyProductArgs#OrderBy
解决这个问题的方法是使用自定义缩放器(我认为),但是 type-GraphQL documentation 只提供了一个例子,其中只有一个变量被接受,但我想接受一个对象使用 2 个键(在本例中为 take 和 skip)。我将如何编写一个接受对象的调用程序,例如这样的分页对象:
{
take: 10
skip: 5
}
ArgsType
装饰器在 Args
(Source) 中注入后将所有内容展平。我建议像这样使用 InputType
装饰器:
@InputType()
class OrderByInputType {
@Field()
fieldName: string;
@Field()
direction: DirectionEnum;
}
@InputType()
class PaginationInputType {
@Field(() => Int)
take: number;
@Field(() => Int)
skip: number;
}
然后将它们作为可选参数传递,如下所示:
companyProducts(
@Arg("OrderBy", { nullable: true }) OrderBy?: OrderByInputType,
@Arg("Pagination", { nullable: true }) Pagination?: PaginationInputType
)
您可能会以更简洁或更紧凑的方式执行此操作,但这应该可行,您可以从这里开始尝试!