Skip to content

Commit

Permalink
forcedRollback for tests
Browse files Browse the repository at this point in the history
  • Loading branch information
golergka committed Apr 23, 2021
1 parent 13a70ae commit 9fe0365
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
11 changes: 11 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,17 @@ describe(`tx`, () => {
expect(committed.thing).toEqual('comitted')
})

it(`doesn't commit changes with forcedRollback`, async () => {
await tx(pg, async (db) => {
db.query(`INSERT INTO things (thing) VALUES ('comitted')`)
})

const { rowCount } = await pg.query(
`SELECT id, thing FROM things WHERE thing = 'node_error'`
)
expect(rowCount).toBe(0)
})

it(`doesn't commit changes when there's a Node exception`, async () => {
await expect(
tx(pg, async (db) => {
Expand Down
17 changes: 12 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,28 @@
import { Pool, PoolClient } from 'pg'
import { ProxyClient } from './proxy_client'

/**
* @param pg node postgres pool
* @param callback callback that will use provided transaction client
* @param forceRollback force rollback even without errors - useful for integration tests
* @returns
*/
export default async function tx<T>(
pg: Pool,
callback: (db: PoolClient) => Promise<T>
callback: (db: PoolClient) => Promise<T>,
forceRollback?: boolean
): Promise<T> {
const client = await pg.connect()
const client = await pg.connect()
const proxyClient = new ProxyClient(client)
await proxyClient.query(`BEGIN`)

try {
const result = await callback(proxyClient)
proxyClient.proxyRelease()
await client.query(`COMMIT`)
proxyClient.proxyRelease()
await client.query(forceRollback ? `ROLLBACK` : `COMMIT`)
return result
} catch (e) {
proxyClient.proxyRelease()
proxyClient.proxyRelease()
await client.query(`ROLLBACK`)
throw e
} finally {
Expand Down

0 comments on commit 9fe0365

Please sign in to comment.