繁体   English   中英

Type-GraphQL 将分页 object 添加到解析器

[英]Type-GraphQL adding pagination object to resolver

我创建了一个 GraphQL 解析器,它使用 TypeORM 搜索公司对象,我希望允许客户端(可选)使用分页或排序对象进行查询,所以我编写了这个解析器:

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

但运行此返回:

错误:您需要为 CompanyProductArgs#OrderBy 提供显式类型

解决这个问题的方法是使用自定义缩放器(我认为),但 type-GraphQL 文档仅提供一个示例,其中仅接受一个变量,但我想接受带有 2 个键的 object案子)。 我将如何编写一个接受 object 的分页器,例如像这样的分页 object:

{
   take: 10
   skip: 5
}

一旦注入Args ( Source ), ArgsType装饰器就会展平所有内容。 我建议像这样使用InputType装饰器:

@InputType()
class OrderByInputType {
  @Field()
  fieldName: string;

  @Field()
  direction: DirectionEnum;
}

@InputType()
class PaginationInputType {
  @Field(() => Int)
  take: number;

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

然后将它们作为可选的 arguments 传递,如下所示:

companyProducts(
    @Arg("OrderBy", { nullable: true }) OrderBy?: OrderByInputType,
    @Arg("Pagination", { nullable: true }) Pagination?: PaginationInputType
  )

您可能可以以更清洁或更紧凑的方式执行此操作,但这应该可以工作,您可以从这里开始玩!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM