Reputation: 227
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
}
Upvotes: 0
Views: 2703
Reputation: 141
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!
Upvotes: 2