npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@wistle/postgres

v1.0.0

Published

Postgres database client for Node.js

Downloads

5

Readme

Wistle Postgres Provider

Overview

Wistle Postgres Provider is a Node.js library designed to manage multiple PostgreSQL database connections efficiently. It supports master and read replica configurations, automatic transaction handling, load balancing for read replicas, and health checks for all database connections.This is designed for node.js applications using Postgres for CURD Operations at high scale.

Features

  • Centralized management of multiple PostgreSQL database connections.
  • Support for master and read replica configurations.
  • Automatic transaction handling.
  • Read replica load balancing.
  • Health checks for all database connections.
  • Graceful shutdown of all connections.

Installation

Install the package via NPM:

npm install @wistle/postgres

Usage

1. Define Configuration

Define the configuration for your databases, including the master and optional read replicas.

import { DatabaseProviderConfig } from "postgres-provider";

const config: DatabaseProviderConfig = {
    userDb: {
        main: {
            user: "username",
            host: "localhost",
            database: "userdb",
            password: "password",
            port: 5432,
        },
        replicas: [
            {
                user: "username",
                host: "replica1.local",
                database: "userdb",
                password: "password",
                port: 5432,
            },
            {
                user: "username",
                host: "replica2.local",
                database: "userdb",
                password: "password",
                port: 5432,
            },
        ],
    },
    orderDb: {
        main: {
            user: "username",
            host: "localhost",
            database: "orderdb",
            password: "password",
            port: 5432,
        },
    },
};

2. Create Database Provider

Set up the PostgresProvider with your database configurations.

import { PostgresProvider } from "postgres-provider";

PostgresProvider.addConnections(config);

3. Retrieve Connection and Execute Queries

Retrieve a connection and perform database operations.

import { PostgresProvider } from "postgres-provider";

async function performDatabaseOperations() {
    const userDb = PostgresProvider.getConnection("userDb");

    // Executing a query
    const result = await userDb.executeQueryOnPool("SELECT * FROM users");
    console.log(result.rows);

    // Executing a query on read replica
    const readResult = await userDb.executeQueryOnReadReplicaPool("SELECT * FROM users");
    console.log(readResult.rows);

    // Transaction example
    const client = await userDb.getConnectionWithTransaction();
    try {
        await userDb.executeQueryOnPool("INSERT INTO users (name) VALUES ($1)", ["John Doe"], client);
        await userDb.commitTransaction(client);
    } catch (error) {
        await userDb.rollbackTransaction(client);
        throw error;
    }
}

performDatabaseOperations().catch(console.error);

4. Health Check

Check the health of all database connections.

import { PostgresProvider } from "postgres-provider";

async function checkDatabaseHealth() {
    try {
        await PostgresProvider.checkAllConnectionsHealth();
        console.log("All connections are healthy");
    } catch (error) {
        console.error("Some connections are unhealthy", error);
    }
}

checkDatabaseHealth().catch(console.error);

5. Graceful Shutdown

Close all connections gracefully when shutting down the application.

import { PostgresProvider } from "postgres-provider";

async function shutdown() {
    await PostgresProvider.closeAllConnections();
    console.log("All connections closed");
}

process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);

Classes and Methods

PostgresService

Methods

  • getConnectionWithTransaction(isolationLevel: string): Promise<PoolClient>
  • executeQueryOnPool<T>(queryText: string, params?: any[], connection?: PoolClient): Promise<QueryResult<T>>
  • executeQueryOnPoolFlaggedReadOnly<T>(queryText: string, params?: any[], readOnly: boolean, connection?: PoolClient): Promise<QueryResult<T>>
  • executeQueryOnReadReplicaPool<T>(queryText: string, params?: any[]): Promise<QueryResult<T>>
  • commitTransaction(client: PoolClient): Promise<void>
  • rollbackTransaction(connection: PoolClient): Promise<void>
  • close(): Promise<void>
  • checkHealth(): Promise<boolean>

PostgresProvider

Provider Methods

  • static addConnections(config: DatabaseProviderConfig): void
  • static getConnection(connectionName: string): PostgresService
  • static async checkAllConnectionsHealth(): Promise<void>
  • static async closeAllConnections(): Promise<void>

Best Practices

  • Always release connections back to the pool.
  • Perform health checks to ensure all connections are active.
  • Gracefully shut down connections when the application terminates.
  • Use appropriate error handling around database operations.

Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

License

This project is licensed under the MIT License.