pxlsspace / PxlsBot

Modular Discord bot
ISC License
4 stars 2 forks source link

Add `database.withConnection(fn)` #22

Closed netux closed 3 years ago

netux commented 3 years ago

Utility function to create a temporary PoolClient connection which is always released once the argument function ends.

Usage:

import { PoolClient } from 'pg';

import * as database from 'database.ts';

const result = await database.withConnection((connection: PoolClient) => connection.query('SELECT * FROM my_table'));

async function getPrefix(connection: PoolClient, guildID: string) {
  const { rows } = await connection.query('SELECT prefix FROM config WHERE guild_id = $1', [guildID]);
  return rows.length > 0 ? rows[0].prefix : DEFAULT_PREFIX;
}
const prefix = await database.withConnection(getPrefix, guildID);