【问题标题】:Type-GraphQL adding pagination object to resolverType-GraphQL 将分页对象添加到解析器
【发布时间】:2020-07-28 21:07:41
【问题描述】:

我创建了一个使用 TypeORM 搜索 Company 对象的 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);
  }
}

但是运行它会返回:

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

解决这个问题的方法是使用自定义缩放器(我认为),但类型 GraphQL documentation 仅提供一个示例,其中仅接受一个变量,但我想接受一个带有 2 个键的对象(在这种情况下采取并跳过)。我将如何编写一个接受对象的调用程序,例如这样的分页对象:

{
   take: 10
   skip: 5
}

【问题讨论】:

    标签: typescript graphql typegraphql


    【解决方案1】:

    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
      )
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 2020-02-21
      • 2018-10-23
      • 2019-10-24
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多