UNPKG

pg-db-libs

Version:

A TypeScript library for calling PostgreSQL functions and procedures with entity mapping

29 lines (27 loc) 1.02 kB
import { Client, ClientConfig } from "pg"; export class PgEntityMapper { /** * Maps a database row to an entity by matching keys to the instance properties. * @param row The database row to map. * @param entityInstance An instance of the entity to use for property mapping. * @returns The mapped entity instance. */ static mapToEntity<T extends object>(row: any, entityInstance: T): T { const entity = { ...entityInstance }; Object.keys(row).forEach((key) => { if (key in entity) { (entity as any)[key] = row[key]; } }); return entity as T; } /** * Maps a list of rows to entity instances. * @param rows The list of database rows. * @param entityInstance An instance of the entity to use for property mapping. * @returns A list of mapped entity instances. */ static mapToEntities<T extends object>(rows: any[], entityInstance: T): T[] { return rows.map((row) => this.mapToEntity(row, entityInstance)); } }