pg-db-libs
Version:
A TypeScript library for calling PostgreSQL functions and procedures with entity mapping
62 lines (55 loc) • 2.28 kB
text/typescript
import { Client, ClientConfig } from "pg";
import { PgEntityMapper } from "./PgEntityMapper";
export class PgFunctionProcedureClient {
private client: Client;
constructor(config: ClientConfig) {
this.client = new Client(config);
}
async connect(): Promise<void> {
await this.client.connect();
}
async disconnect(): Promise<void> {
await this.client.end();
}
/**
* Calls a PostgreSQL function or procedure and maps the result to the specified entity type.
* Handles functions/procedures with output parameters and result sets.
* @param functionName The name of the function or procedure.
* @param params The parameters to pass.
* @param entityConstructor The constructor of the entity to map to (class).
* @param {boolean} isFunction - Whether the callable is a function (true) or a procedure (false).
* @param hasOutputParameters Whether the function/procedure returns output parameters.
* @returns A list of entities mapped from the result or an object of output parameters.
*/
async callFunctionOrProcedure<T extends object>(
functionName: string,
params: any[],
entityConstructor: new () => T,
isFunction = false,
hasOutputParameters = false
): Promise<T[] | Record<string, any>> {
const placeholders = params.map((_, index) => `$${index + 1}`).join(", ");
const query = isFunction
? `SELECT * FROM ${functionName}(${placeholders})`
: `CALL ${functionName}(${placeholders})`;
try {
const result = await this.client.query(query, params);
if (hasOutputParameters) {
// For output parameters, return the first row as an object
if (result.rows.length > 0) {
return result.rows[0];
}
return {};
}
// For result sets, map the rows to entities
const entityInstance = new entityConstructor();
return PgEntityMapper.mapToEntities(result.rows, entityInstance);
} catch (error) {
console.error(
`Error calling function or procedure ${functionName}:`,
error
);
throw error;
}
}
}