Skip to content

Commit c46b857

Browse files
committed
feat(builder): add afterRollback hook
1 parent bcfa002 commit c46b857

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

packages/sqlite-builder/src/builder.ts

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,16 @@ function isSelectQueryBuilder<DB, O>(
3636
return builder.toOperationNode().kind === 'SelectQueryNode'
3737
}
3838

39-
type TransactionOptions = {
39+
type TransactionOptions<T> = {
4040
errorMsg?: string
4141
/**
4242
* after commit hook
4343
*/
44-
afterCommit?: () => Promisable<void>
44+
afterCommit?: (result: T) => Promisable<void>
45+
/**
46+
* after rollback hook
47+
*/
48+
afterRollback?: (err: unknown) => Promisable<void>
4549
}
4650

4751
export class SqliteBuilder<DB extends Record<string, any>> {
@@ -156,15 +160,14 @@ export class SqliteBuilder<DB extends Record<string, any>> {
156160

157161
private logError(e: unknown, errorMsg?: string) {
158162
errorMsg && this.logger?.error(errorMsg, e instanceof Error ? e : undefined)
159-
return undefined
160163
}
161164

162165
/**
163166
* run in transaction, support nest call (using savepoint)
164167
*/
165168
public async transaction<O>(
166169
fn: (trx: Transaction<DB>) => Promise<O>,
167-
options: TransactionOptions = {},
170+
options: TransactionOptions<O> = {},
168171
): Promise<O | undefined> {
169172
if (!this.trx) {
170173
return await this.kysely.transaction()
@@ -174,20 +177,29 @@ export class SqliteBuilder<DB extends Record<string, any>> {
174177
return await fn(trx)
175178
})
176179
.then(async (result) => {
177-
await options.afterCommit?.()
180+
await options.afterCommit?.(result)
178181
return result
179182
})
180-
.catch(e => this.logError(e, options.errorMsg))
183+
.catch(async (e) => {
184+
await options.afterRollback?.(e)
185+
this.logError(e, options.errorMsg)
186+
return undefined
187+
})
181188
.finally(() => this.trx = undefined)
182189
}
190+
183191
this.trxCount++
184192
this.logger?.debug(`run in savepoint: sp_${this.trxCount}`)
185193
return await runWithSavePoint(this.trx!, fn, `sp_${this.trxCount}`)
186194
.then(async (result) => {
187-
await options.afterCommit?.()
195+
await options.afterCommit?.(result)
188196
return result
189197
})
190-
.catch(e => this.logError(e, options.errorMsg))
198+
.catch(async (e) => {
199+
await options.afterRollback?.(e)
200+
this.logError(e, options.errorMsg)
201+
return undefined
202+
})
191203
.finally(() => this.trxCount--)
192204
}
193205

0 commit comments

Comments
 (0)