Skip to content

Commit

Permalink
fix: pool does not need connect
Browse files Browse the repository at this point in the history
  • Loading branch information
Alan Shaw committed Feb 28, 2022
1 parent 8b8e817 commit 1db831e
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 8 deletions.
9 changes: 3 additions & 6 deletions packages/cron/src/bin/metrics.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,13 @@ import path from 'path'
import { fileURLToPath } from 'url'
import dotenv from 'dotenv'
import { updateMetrics } from '../jobs/metrics.js'
import { getPg } from '../lib/utils.js'
import { getPgPool } from '../lib/utils.js'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

async function main() {
const rwPg = getPg(process.env, 'rw')
const roPg = getPg(process.env, 'ro')

await rwPg.connect()
await roPg.connect()
const rwPg = getPgPool(process.env, 'rw')
const roPg = getPgPool(process.env, 'ro')

try {
await updateMetrics({ rwPg, roPg })
Expand Down
2 changes: 1 addition & 1 deletion packages/cron/src/jobs/metrics.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
const log = debug('metrics:updateMetrics')

/**
* @typedef {import('pg').Client} Client
* @typedef {import('pg').Pool} Client
* @typedef {{ name: string, value: number }} Metric
*/

Expand Down
20 changes: 19 additions & 1 deletion packages/cron/src/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,24 @@ export function getDBClient(env) {
* @param {'ro'|'rw'} [mode]
*/
export function getPg(env, mode = 'rw') {
return new pg.Client({ connectionString: getPgConnString(env, mode) })
}

/**
* Create a new Postgres pool instance from the passed environment variables.
* @param {Record<string, string|undefined>} env
* @param {'ro'|'rw'} [mode]
*/
export function getPgPool(env, mode = 'rw') {
return new pg.Pool({ connectionString: getPgConnString(env, mode) })
}

/**
* Get a postgres connection string from the passed environment variables.
* @param {Record<string, string|undefined>} env
* @param {'ro'|'rw'} [mode]
*/
function getPgConnString(env, mode = 'rw') {
let connectionString
if (env.ENV === 'production') {
connectionString =
Expand All @@ -97,5 +115,5 @@ export function getPg(env, mode = 'rw') {
mode === 'rw' ? env.DATABASE_CONNECTION : env.RO_DATABASE_CONNECTION
}
if (!connectionString) throw new Error('missing Postgres connection string')
return new pg.Pool({ connectionString, allowExitOnIdle: true })
return connectionString
}

0 comments on commit 1db831e

Please sign in to comment.