pg-db-libs
Version:
A TypeScript library for calling PostgreSQL functions and procedures with entity mapping
66 lines (65 loc) • 3.29 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PgFunctionProcedureClient = void 0;
const pg_1 = require("pg");
const PgEntityMapper_1 = require("./PgEntityMapper");
class PgFunctionProcedureClient {
constructor(config) {
this.client = new pg_1.Client(config);
}
connect() {
return __awaiter(this, void 0, void 0, function* () {
yield this.client.connect();
});
}
disconnect() {
return __awaiter(this, void 0, void 0, function* () {
yield 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.
*/
callFunctionOrProcedure(functionName_1, params_1, entityConstructor_1) {
return __awaiter(this, arguments, void 0, function* (functionName, params, entityConstructor, isFunction = false, hasOutputParameters = false) {
const placeholders = params.map((_, index) => `$${index + 1}`).join(", ");
const query = isFunction
? `SELECT * FROM ${functionName}(${placeholders})`
: `CALL ${functionName}(${placeholders})`;
try {
const result = yield 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_1.PgEntityMapper.mapToEntities(result.rows, entityInstance);
}
catch (error) {
console.error(`Error calling function or procedure ${functionName}:`, error);
throw error;
}
});
}
}
exports.PgFunctionProcedureClient = PgFunctionProcedureClient;