CasperLeerinkC
Convex Community4mo ago
17 replies
CasperLeerink

Can't wrap my head around paginated queries with advanced filters

I have this complex query:

export const listAvailable = protectedQuery({
  args: {
    searchQuery: v.optional(v.string()),
    cursor: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = 5;
    const providerServices = await ctx.db
      .query("providerServices")
      .withIndex("by_provider", (q) => q.eq("providerId", ctx.profile._id))
      .collect();
    const providerServiceIds = providerServices.map(
      (service) => service.serviceId,
    );
    const quotes = await ctx.db
      .query("quotes")
      .withIndex("by_provider", (q) => q.eq("providerId", ctx.profile._id))
      .filter((q) => q.eq("status", "Pending"))
      .collect();
    const quotedRequestIds = quotes.map((quote) => quote.requestId);
    const serviceRequests = await ctx.db
      .query("serviceRequests")
      .withIndex("by_creation_time", (q) =>
        args.cursor ? q.lte("_creationTime", args.cursor) : q,
      )
      .order("desc")
      .filter((q) => {
        return q.and(
          q.eq("status", "pending"),
          q.inArray("serviceId", providerServiceIds),
          q.notInArray("id", quotedRequestIds),
        );
      })
      .take(limit + 1);

    let nextCursor: typeof args.cursor = undefined;
    if (serviceRequests.length > limit) {
      const nextItem = serviceRequests.pop();
      nextCursor = nextItem?._creationTime;
    }
    return {
      items: serviceRequests,
      nextCursor,
    };
  },
});


Now the q.inArray or q.notInArray does not exist unfortunately.

The docs say that you have to do it in javascript, but then you have to use collect() instead of take as otherwise it might filter out the records and end up with an empty page result.

Is .collect() method and then filtering in js indeed the right option? In this case it would have to read through the whole table whereas with it would just loop until it has the 6 first rows
Was this page helpful?