backpack1098B
Convex Community3y ago
5 replies
backpack1098

prefix search question + how to return top 5 if searchInput is empty?

hi team! does anyone know how can i simplify the following code such that it returns the first 5 entries if the searchInput is empty? is there a way to searchInput === undefined -> skip the withSearchIndex? thanks!
export const searchCustomers = query({
  args: {
    searchInput: v.string(),
  },
  handler: async (ctx, args) => {
    const business = await getBusiness(ctx, {})
    if (!args.searchInput) {
      return await ctx.db
        .query(CUSTOMER_DB)
        .withIndex("by_businessId", (q) =>
          q.eq("businessId", business._id)
        )
        .take(5)
    }
    const customers = await ctx.db
      .query(CUSTOMER_DB)
      .withSearchIndex("search_name", (q) =>
        q.search("name", args.searchInput).eq("businessId", business._id)
      )
      .collect()
    return customers
  },
})
Was this page helpful?