winsoroaks
winsoroaks•14mo ago

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
},
})
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
},
})
5 Replies
erquhart
erquhart•14mo ago
I wouldn't simplify it any further than this, personally. If you fight the urge to optimize as you go, you'll start moving really fast with convex. I recommend building up a bit of tech debt and then going back to pay it off when you start to really feel it. I find this approach gives me more context, I make better decisions, and waste less time on "improvements" that I grow out of quickly.
winsoroaks
winsoroaksOP•14mo ago
yea makes sense. i just find myself repeating this pattern quite a few times 😅 thanks for the perspective!
erquhart
erquhart•14mo ago
For sure - the team may have insights to add, that’s just my take.
Michal Srb
Michal Srb•14mo ago
It does look pretty clean, can you elaborate on your concern? (What you dislike about this code) The only repetition I see is ctx.db.query() which you could put in a variable, but I don’t think it would make the code more readable. Perhaps if you have similar code elsewhere you want to abstract at a higher layer?
winsoroaks
winsoroaksOP•14mo ago
ah okay, i'll leave it as is for now. thanks 🙂

Did you find this page helpful?