-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathindex.ts
More file actions
42 lines (34 loc) · 901 Bytes
/
index.ts
File metadata and controls
42 lines (34 loc) · 901 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { Client } from 'pg'
async function doTransaction(client: Client) {
await client.query('BEGIN')
let shouldRollback = false
let disposed = false
return {
async [Symbol.asyncDispose]() {
if (disposed) return
disposed = true
if (shouldRollback) {
await client.query('ROLLBACK')
} else {
await client.query('COMMIT')
}
},
rollback() {
shouldRollback = true
},
}
}
// Auto-rollback wrapper that catches errors automatically
async function transaction<T>(client: Client, fn: () => Promise<T>): Promise<T> {
await using txn = await doTransaction(client)
try {
const result = await fn()
// If we get here, success - transaction will auto-commit
return result
} catch (error) {
// If error occurs, mark for rollback
txn.rollback()
throw error
}
}
export { transaction as transaction }