chad
chad
KKysely
Created by chad on 7/30/2024 in #help
select / groupBy combined helper
I realize this usecase looks awful, but our API takes an input of a list of fields to group by, which also means it will return those fields in the result. What I have works, but there's a lot of duplication:
.$if(isGroupedBy(STOP_ID), (qb) =>
qb.select('stopid as stopId').groupBy('stopid'),
)
.$if(isGroupedBy(STOP_ID), (qb) =>
qb.select('stopid as stopId').groupBy('stopid'),
)
but these 3 lines are repeated for each possible parameter a dozen times; and some are more complicated such as extracting multiple fields out of a timestamp. I would prefer something like this but I can't figure out how to get it to typecheck
const selectAndGroupBy = (qb: SelectQueryBuilder<Database, 'person', any>,
selection: SelectExpression<Database, 'person'>
) => qb.select(selection).groupBy(selection);

const groupBys = ['age']

const person = await db
.selectFrom('person')
.select(['id', 'first_name'])
.$if(groupBys.includes('age'), (qb) => selectAndGroupBy(qb, 'age'))
const selectAndGroupBy = (qb: SelectQueryBuilder<Database, 'person', any>,
selection: SelectExpression<Database, 'person'>
) => qb.select(selection).groupBy(selection);

const groupBys = ['age']

const person = await db
.selectFrom('person')
.select(['id', 'first_name'])
.$if(groupBys.includes('age'), (qb) => selectAndGroupBy(qb, 'age'))
Playground here: https://kyse.link/C4mRA
6 replies