I’m trying to write a query builder function in Drizzle using findMany() function that handles pagination and parameter request.
The issue is, i’m unable to use orderBy in “with”.
The function I made is:
export const paginate = async <
TSchema extends TablesRelationalConfig,
TFields extends TableRelationalConfig,
>(
qb: RelationalQueryBuilder<TSchema, TFields>,
model: PgTable,
requestQuery: ListSchema,
allowedFilters: Record<string, string | ((column: any, value: any) => SQL)>,
) => {
const columns = getTableColumns(model);
const {
page = 1,
perPage = 25,
orderBy,
sort = "asc",
...filters
} = requestQuery;
const validSort = sort.toLowerCase() === "asc" ? asc : desc;
const validOrderBy =
orderBy && orderBy in columns ? (orderBy as keyof typeof columns) : "id";
const whereClause = buildWhereClause(filters, model, allowedFilters);
const data = await qb.findMany({
limit: perPage,
offset: (page - 1) * perPage,
orderBy: validSort(columns[validOrderBy]),
where: whereClause,
with: {
models: {
with: {
prints: true,
},
},
status: {
limit: 1,
orderBy: (status, { desc }) => [desc(status.createdAt)],
},
},
});
const c = await db.select({ count: count() }).from(model).where(whereClause);
return {
data,
count: c[0].count,
};
};
But im getting error at status.createdAt:
TS2339: Property createdAt does not exist on type
{ [K in keyof ([FindTableByDBName<TSchema, TFields[“relations”][“status”][“referencedTableName”]>[“columns”]] extends [never] ? {} : FindTableByDBName<TSchema, TFields[“relations”][“status”][“referencedTableName”]>[“columns”])]: ([…] extends […] ? {} : FindTableByDBName<…>[“columns”])[K]; }
P.S, overall goal is to have the with outside and pass to this function to make it more dynamic, but i still stuck here.
would be grateful if you help me on this.
Thanks.
user2902222 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.