简体   繁体   中英

Type-GraphQL adding pagination object to resolver

I've created a GraphQL resolver which searches for Company objects using TypeORM, I would like the to allow the client to (optionality) query with pagination or order objects so I wrote this resolver:

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

But running this returns:

Error: You need to provide explicit type for CompanyProductArgs#OrderBy

The way to solve this would be using a Custom Scalers (I think), but the type-GraphQL documentation only provide one example in which only one variable gets accepted, but I want to accept an object with 2 keys (take and skip in this case). How would I write a scaller that accepts object such as a pagination object like this:

{
   take: 10
   skip: 5
}

The ArgsType decorator flattens everything once injected in Args ( Source ). I'd recommend using the InputType decorator like this:

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

  @Field()
  direction: DirectionEnum;
}

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

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

And then passing them as optional arguments like so:

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

You could probably do this in a cleaner or compacter way but this should work and you can play around from here!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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