pg-database
TypeScript icon, indicating that this package has built-in type declarations

2.1.19 • Public • Published

pg-database

Overview

Handy wrapper for pg (formerly node-postgres) database connection instances featuring:

  • CRUD operation wrappers
  • named placeholders
  • query logging

You can import and instantiate database connection manually:

import Database from 'pg-database';
const database = new Database('<connection-uri>', console.log);

You can import an "automatically instantiated" database providing DB_URI=<connection-uri> and DB_LOG=<1|> environment variables:

import { database } from 'pg-database';

You can use this module as a simple drop-in replacement for pg.
Original pool, query and close methods are bound as they are.

import { database } from 'pg-database';

const client = await database.pool.connect();
client.query('LISTEN events');
client.on('notification', console.log);
client.on('error', console.error);
await client.release();

CRUD

Check out src/index.ts to get a picture of available methods: minimal and simple.

Named placeholders

You can use object for replacements (named placeholders) instead of array replacements (positional placeholders).
Placeholders must begin with : or $ and can contain only letters, numbers, underscores, dashes.

Before:

client.query('SELECT name FROM people WHERE name = $1', ['john'])

After:

client.query('SELECT name FROM people WHERE name = :name', { name: 'john' })

Query logging

You can log executed queries.

Either create your db instance with a customer logger:

const database = new Database('<connection-uri>', console.log);

Or use the automatic instance setting DB_URI=<connection-uri> and DB_LOG=1 env variables:

import { database } from 'pg-database';

Development

To run tests locally:

# start db
docker run --rm --name pg-database-test -p 5432:5432 --detach --env POSTGRES_USER=root --env POSTGRES_PASSWORD=root --env POSTGRES_DB=test postgres:14-alpine postgres -c log_statement=all

# run tests
yarn test

# remove db
docker rm -f pg-database-test

Readme

Keywords

none

Package Sidebar

Install

npm i pg-database

Weekly Downloads

3

Version

2.1.19

License

MIT

Unpacked Size

25.1 kB

Total Files

18

Last publish

Collaborators

  • damianobarbati