Reputation: 31
I'm building an abstract base repository class using Drizzle ORM for a PostgreSQL database. The repository is generic and works with any table extending PgTable, and the primary key is passed dynamically. Here's the relevant part of my implementation:
async findOne(id: T['$inferSelect'][ID]): Promise<InferSelectModel<T>> {
if (!id) {
throw new Error('ID is required');
}
const result = await this.db
.select()
.from(this.table)
.where(eq(sql.raw(`${this.primaryKey.toString()}`), id));
if (!result.length) {
throw new Error(`No record found for ID: ${id}`);
}
return result[0];
}
The sql.raw(${this.primaryKey.toString()})
usage is not type-safe, which defeats the purpose of using TypeScript for strict typing. If the primaryKey string doesn't match the actual column name in the table, it will only throw runtime errors.
I want a solution that ensures the primary key is type-safe and can be correctly validated at compile-time.
Here's the constructor for additional reference:
constructor(
protected readonly db: DrizzleDB,
protected readonly table: T,
protected readonly primaryKey: ID,
) {}
Upvotes: 3
Views: 160