UNPKG

multibridge

Version:

A multi-database connection framework with centralized configuration

57 lines (56 loc) 2.62 kB
"use strict"; 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()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createPostgresConnection = createPostgresConnection; const pg_1 = require("pg"); const loggers_1 = __importDefault(require("../utils/loggers")); function createPostgresConnection(config) { return __awaiter(this, void 0, void 0, function* () { const pool = new pg_1.Pool({ host: config.host, port: config.port, user: config.username, password: config.password, database: config.database, idleTimeoutMillis: 600000, // e.g., 10 minutes, adjust as needed connectionTimeoutMillis: 5000, // e.g., 5 seconds }); // For every new connection, set the search_path pool.on("connect", (client) => __awaiter(this, void 0, void 0, function* () { try { yield client.query(`SET search_path TO ${config.schema}`); loggers_1.default.info(`Search path set to ${config.schema} for new connection`); } catch (error) { loggers_1.default.error(`Failed to set search path on new connection: ${error.message}`); } })); // Test the pool by acquiring a client once try { const client = yield pool.connect(); try { yield client.query(`SET search_path TO ${config.schema}`); loggers_1.default.info("Connected to PostgreSQL and search_path set"); } finally { client.release(); } return pool; } catch (error) { loggers_1.default.error(`Error establishing initial connection to PostgreSQL: ${error.message}`); throw error; } }); }