Irosha Hewage
Irosha Hewage

Reputation: 31

How to Ensure Type-Safe Querying with Drizzle ORM in a Base Repository's Primary Key Handling?

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 Problem:

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.

Additional Context:

Here's the constructor for additional reference:

constructor(
  protected readonly db: DrizzleDB,
  protected readonly table: T,
  protected readonly primaryKey: ID,
) {}
  1. How can I make the where() clause for the primary key type-safe in this context?
  2. Is there a better approach or pattern for handling dynamic primary keys in a repository class with Drizzle ORM?

Upvotes: 3

Views: 160

Answers (0)

Related Questions