Generic Types for Select #2596
Replies: 1 comment
|
You can get the types from schema like this: base.repository type Schema = ExtractTablesWithRelations<typeof schema>;
type OmitSensitive<T, K extends keyof any> = Omit<T, Extract<keyof T, K>>;
export abstract class BaseRepository<
TName extends keyof Schema,
TTable extends PgTableWithColumns<any>,
TSensitiveFields extends keyof InferSelectModel<TTable> = never,
> {
protected abstract sensitiveFields: readonly TSensitiveFields[];
protected constructor(
protected readonly db: DbClient,
protected readonly tableName: TName,
protected readonly table: TTable,
) {}user.repository.ts // Exclude password from SelectUser type
export type SelectUser = Omit<InferSelectModel<typeof users>, 'passwordHash'>;
export type SelectUserWithPassword = InferSelectModel<typeof users>;
export type CreateUser = InferInsertModel<typeof users>;
export type UpdateUser = Partial<CreateUser>;
const excludeFields = [
'passwordHash',
] as const satisfies readonly (keyof typeof users.$inferSelect)[];
@Injectable()
export class UserRepository extends BaseRepository<
'users',
typeof users,
(typeof excludeFields)[number]
> {
// Define sensitive fields that should be excluded by default
protected sensitiveFields = excludeFields;
constructor(@Inject(DRIZZLE) readonly db: DbClient) {
super(db, 'users', users);
} |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
I'm trying to make a generic base repository which will be a wrapper around drizzle. I have
baseRepositorylike:and my typings look like this:
I'm getting an error on .select that my types don't match, although I have exact types listed as below:
What could I be doing wrong?
All reactions