@salsita/psql

1.0.3 • Public • Published

@salsita/psql

NPM version Downloads Licence Dependency Status devDependency Status

Functions and utilities for wrapping postgres DB connection.

  • connect - accepts function and executes it passing DB connection as parameter.
  • transaction - wraps function call to DB transaction
  • withDb - ensures first parameter of function is DB connection

Example:

const _ = require("lodash");
const squel = require("squel");
const psql = require("@salsita/psql");
const onlyFirstRow = require("@salsita/sql/utils/onlyFirstRow");
const quote = require("@salsita/sql/utils/quote");

//
// CONFIGURATION
//

const connect = psql.connect({ options: { connectionString: process.env.DATABASE_URL } });
const withDb = psql.withDb(connect);
const { transaction } = psql;

const usersModel = _.mapValues(
  {
    findById: onlyFirstRow((dbClient, id) =>
      dbClient.query(
        squel
          .select()
          .from('"Users"')
          .where('"userId" = ?', id)
          .toParam()
      )
    ),
    updateById: onlyFirstRow((dbClient, id, data) =>
      dbClient.query(
        squel
          .update()
          .table('"Users"')
          .setFields(quote(data))
          .where('"userId" = ?', id)
          .returning("*")
          .toParam()
      )
    )
  },
  withDb
);

//
// USAGE
//

// random connection from pool
const user = await usersModel.findById(1);

// using one connection for all queries in transaction
const user = await connect(
  transaction(async dbClient => {
    const oldUser = await usersModel.findById(dbClient, 1);
    const newUser = await usersModel.updateById(dbClient, 1, { name: `${oldUser.name}son` });
  })
);

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.3
    0
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.0.3
    0
  • 1.0.2
    0
  • 1.0.1
    0
  • 1.0.0
    0

Package Sidebar

Install

npm i @salsita/psql

Weekly Downloads

0

Version

1.0.3

License

MIT

Unpacked Size

6.61 kB

Total Files

10

Last publish

Collaborators