dannyeloD
Convex Community2y ago
10 replies
dannyelo

Cleanest way to handle optional filters

Hello,
I need to filter orders table by status

/orders route should get all orders
/orders?status=pending should get orders with the status of 'pending'

What should I pass to ignore the filter?
I tried this and is not working.

export const getOrders = query({
  args: {
    organizationId: v.optional(v.id('organizations')),
    status: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const orders = await ctx.db
      .query('orders')
      .filter((q) => q.eq(q.field('organizationId'), args.organizationId))
      .filter((q) => {
        if (!args.status) {
          return null
        }
        return q.eq(q.field('status'), args.status)
      })
      .collect()

    const mappedOrders = await Promise.all(
      orders.map(async (order) => {
        return await transformOrderForClient(order, ctx)
      }),
    )
    return mappedOrders
  },
})
Was this page helpful?