簡體   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