Drizzle – Convert pg SelectedFields to plain type

I’m currently using Drizzle in a project and have implemented a repository pattern for the connection with Drizzle. The issue is that within the base class of the repositories, I have this method which has a ‘select’ property. This property is of type SelectedFields from pg.

export default class BaseRepository<TSchema extends PgTable, ID extends keyof TSchema["$inferSelect"]> {
  
  protected constructor(
    protected schema: TSchema,
    primaryKey: ID
  ) {
    this.primaryColumn = schema[primaryKey as keyof TSchema] as Column<ColumnBaseConfig<ColumnDataType, string>, object, object>;
  }

...

protected async findFirstBy<TSelection = InferSelectModel<TSchema>>({
    criteria,
    select,
    transaction
  }: FindFirstByParams<TSchema>): Promise<(TSelection extends SelectedFields ? TSelection : InferSelectModel<TSchema>) | null> {
    const connection = transaction || (await DrizzleSetup.getDrizzleInstance());

    try {
      let query;
      if (select) {
        query = connection.select(select).from(this.schema);
      } else {
        query = connection.select().from(this.schema);
      }

      const andQuery = this.parseCriteria(criteria);
      if (andQuery.length) query.where(and(...andQuery));

      const [result] = await query;

      return (result as TSelection extends SelectedFields ? TSelection : InferSelectModel<TSchema>) || null;
    } catch (error) {
      throw new DatabaseError("Error fetching record", { debugErrors: { error } });
    }
  }
...
}

And I have this typing:

import { SelectedFields, type PgTable } from "drizzle-orm/pg-core";

export type FindFirstByParams<TSchema extends PgTable> = {
  criteria: QueryCriteria<TSchema>;
  select?: SelectedFields;
  transaction?: DrizzleTransaction;
}

Now, the problem is making the method return the correct typing, that is, not returning the complete schema but only what I’m selecting. Currently, my implementation of the method in the repository is this:

export class ProviderRepository extends BaseRepository<typeof providerSchema, "id"> {
  constructor() {
    super(providerSchema, "id");
  }

getProviderByName(paymentProviderName: string) {

    const select = {
      paymentProviderName: providerSchema.paymentProviderName,
      paymentProviderGateway: providerSchema.paymentGateway
    };

    return this.findFirstBy<typeof select>({
      criteria: {
        paymentProviderName
      },
      select
    });
  }
}

I have two possible cases, the first one is that it returns the whole schema and the typing works correctly this is only posible with out sending the select option.

Promise<{
    id: number;
    paymentProviderName: string;
    paymentGateway: string;
    createdAt: Date;
    updatedAt: Date;
} | null>

The second one returns the typing of the select object, that is:

Promise<{
    paymentProviderName: PgColumn<{
        name: "paymentProviderName";
        tableName: "provider";
        dataType: "string";
        columnType: "PgVarchar";
        data: string;
        driverParam: string;
        notNull: true;
        hasDefault: false;
        enumValues: [...];
        baseColumn: never;
    }, {}, {}>;
    paymentProviderGateway: PgColumn<...>;
} | null>

The issue arises when I try to use the returned object. Obviously, I encounter casting errors because when I try to send, for example, a string, a PgColumn type is sent instead, so the type that I need it’s the first one but with the posibility of use select.

Any suggestion?

I’ve been reviewing the Drizzle code to see if there’s an internal way to convert this select into a flat type, but I couldn’t find anything.

New contributor

CodeRevenge is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật