How can I extract the from/join parts of a complex query into a variable?

Hi 👋

I'm wondering how I can extract those parts for a query, so I can reuse it:

const baseFrom = tx
  .from(postsTbl)
  .innerJoin(authorsTbl, eq(authorsTbl.id, postsTbl.authorId))
  .leftJoin(
    // ... more
  )

// this is then used in 3 separate queries (since I need the non-paginated filtered and unfiltered count of the query)
const mainQuery = tx
  .select({
    ...postsTblColumns,
    author: {
      id: authorTblColumns.id,
      firstName: authorTblColumns.firstName,
      lastName: authorTblColumns.lastName,
    },
    // ... many more
  })

const baseWhere = [
  and(
    eq(postsTbl.category, input.someId),
    input.view
      ? input.view === 'planned'
        ? eq(postsTbl.status, 'planned')
        : ne(postsTbl.status, 'canceled')
      : undefined,
  ),
];

const filterWhere = [
          // advancedWhere ? advancedWhere : undefined,
          input.search
            ? or(
                ilike(authorsTbl.firstName, `%${input.search}%`),
                ilike(authorsTbl.lastName, `%${input.search}%`),
              )
            : undefined,
        ];


const posts = await tx
  .select()
  .from(baseFrom)
  .where(and(...baseWhere, ...filterWhere))
  .limit(input.pageSize)
  .offset(input.pageIndex * input.pageSize);

const totalFilteredCount = await tx
  .select({
    count: countDistinct(postsTbl.id),
  })
  .from(baseFrom)
  .where(and(...baseWhere, ...filterWhere))
  .execute()
  .then((res) => res[0]?.count ?? 0);

const totalUnfilteredCount = await tx
  .select({
    count: countDistinct(postsTbl.id),
  })
  .from(baseFrom)
  .where(and(...baseWhere))
  .execute()
  .then((res) => res[0]?.count ?? 0);
Was this page helpful?