KyselyK
Kysely2y ago
5 replies
chad

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'),
      )

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'))


Playground here:
https://kyse.link/C4mRA
Solution
But here's how you'd do it if you really really want to https://kyse.link/4PswR
Was this page helpful?