UNPKG

@hotmeshio/hotmesh

Version:

Serverless Workflow

103 lines (102 loc) 3.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PostgresConnection = void 0; const __1 = require(".."); class PostgresConnection extends __1.AbstractConnection { constructor() { super(...arguments); this.defaultOptions = { host: 'postgres', port: 5432, user: 'postgres', password: 'password', database: 'hotmesh', max: 20, idleTimeoutMillis: 30000, }; } async createConnection(clientConstructor, options, config = {}) { try { let connection; if (config.provider === 'postgres.poolclient' || PostgresConnection.isPoolClient(clientConstructor)) { // It's a PoolClient connection = clientConstructor; if (config.connect) { const client = await clientConstructor.connect(); //register the connection singularly to be 'released' later PostgresConnection.poolClientInstances.add(client); this.poolClientInstance = client; } } else { // It's a Client connection = new clientConstructor(options); await connection.connect(); await connection.query('SELECT 1'); } //register the connection statically to be 'ended' later PostgresConnection.connectionInstances.add(connection); return connection; } catch (error) { PostgresConnection.logger.error(`postgres-provider-connection-failed`, { host: options.host ?? 'unknown', database: options.database ?? 'unknown', port: options.port ?? 'unknown', error, }); throw new Error(`postgres-provider-connection-failed: ${error.message}`); } } getClient() { if (!this.connection) { throw new Error('Postgres client is not connected'); } return this.poolClientInstance || this.connection; } static async disconnectAll() { if (!this.disconnecting) { this.disconnecting = true; await this.disconnectPoolClients(); await this.disconnectConnections(); this.disconnecting = false; } } static async disconnectPoolClients() { Array.from(this.poolClientInstances.values()).map((instance) => { instance.release(); }); this.poolClientInstances.clear(); } static async disconnectConnections() { Array.from(this.connectionInstances.values()).map((instance) => { instance.end(); }); this.connectionInstances.clear(); } async closeConnection(connection) { //no-op (handled by disconnectAll) } static isPoolClient(client) { return !(isNaN(client?.totalCount) && isNaN(client?.idleCount)); } static async getTransactionClient(transactionClient) { let client; let type; if (PostgresConnection.isPoolClient(transactionClient)) { type = 'poolclient'; client = await transactionClient.connect(); } else { type = 'client'; client = transactionClient; } return [type, client]; } } exports.PostgresConnection = PostgresConnection; //statically track all clients (//call 'release') PostgresConnection.poolClientInstances = new Set(); //statically track all connections (//call 'end') PostgresConnection.connectionInstances = new Set();