How to call a method based on a condition?

I am running two almost similar queries based on a condition. In one of the condition I'm calling the where method and in the other one I'm not. How can I reduce duplicacy by having just one query that works for both conditions? Basically calling the where method only if a condition holds.
if (id === -1)
chunk = await db
.select({
id: posts.id,
content: posts.content,
})
.from(posts)
.orderBy(desc(posts.id))
.limit(6);
else
chunk = await db
.select({
id: posts.id,
content: posts.content,
})
.from(posts)
.where(lt(posts.id, id) && eq(posts.hidden, hidden))
.orderBy(desc(posts.id))
.limit(6);
if (id === -1)
chunk = await db
.select({
id: posts.id,
content: posts.content,
})
.from(posts)
.orderBy(desc(posts.id))
.limit(6);
else
chunk = await db
.select({
id: posts.id,
content: posts.content,
})
.from(posts)
.where(lt(posts.id, id) && eq(posts.hidden, hidden))
.orderBy(desc(posts.id))
.limit(6);
1 Reply
francis
francis8mo ago
uh you can build the query in progress i.e. let query = <first bit>; if (condition) query = query.where....; await query.<last bit>
Want results from more Discord servers?
Add your server