rochel3R
Convex Community2y ago
16 replies
rochel3

Get Price highest to lowest with pagination query

I am currently designing a filter which can take in " sorted by " and apply it to a convex query, there are 4 options,

Sorted by Newest (newest to oldest)
Oldest (oldest to newest)
Price (highest to lowest)
Price (lowest to highest)

There are also additional filters such as categoryId of the products and min / max prices

The paginated query looks like this:

export const getPostList = query({
  args: {
    paginationOpts: paginationOptsValidator,
    categoryId: v.optional(v.id("categories")),
    title: v.optional(v.string()),
    sortedBy: v.string(),
    min: v.optional(v.number()),
    max: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    var res = ctx.db.query("post");

    if (args.categoryId) {
      var res = res.filter((q) => q.eq(q.field("categoryId"), args.categoryId));
    }

    if (args.title) {
      var res = res.filter((q) => q.eq(q.field("title"), args.title));
    }

    if (args.min) {
      var res = res.filter((q) => q.gte(q.field("pricing"), args.min!));
    }

    if (args.max) {
      var res = res.filter((q) => q.lte(q.field("pricing"), args.max!));
    }

    if (args.sortedBy === "oldest") {
      return await res.order("asc").paginate(args.paginationOpts);
    } else if (args.sortedBy === "desc") {
      const x = await res.paginate(args.paginationOpts);
      const ret = x.page.sort((a, b) => b.pricing - a.pricing);
      return x;
    } else if (args.sortedBy === "asc") {
      const x = await res.paginate(args.paginationOpts);
      const ret = x.page.sort((a, b) => a.pricing - b.pricing);
      return x;
    } else {
      return await res.order("desc").paginate(args.paginationOpts);
    }
  },
});


"desc" meaning from Price highest to lowest
"asc" meaning from Price lowest to highest

However this does not provide me with the intended result as it only sorts after the pagination. I have tried using withIndex("by_pricing") but it gives an error saying .withIndex is not a function. Please help! Thanks
Was this page helpful?