@@ -36,12 +36,16 @@ function isSelectQueryBuilder<DB, O>(
36
36
return builder . toOperationNode ( ) . kind === 'SelectQueryNode'
37
37
}
38
38
39
- type TransactionOptions = {
39
+ type TransactionOptions < T > = {
40
40
errorMsg ?: string
41
41
/**
42
42
* after commit hook
43
43
*/
44
- afterCommit ?: ( ) => Promisable < void >
44
+ afterCommit ?: ( result : T ) => Promisable < void >
45
+ /**
46
+ * after rollback hook
47
+ */
48
+ afterRollback ?: ( err : unknown ) => Promisable < void >
45
49
}
46
50
47
51
export class SqliteBuilder < DB extends Record < string , any > > {
@@ -156,15 +160,14 @@ export class SqliteBuilder<DB extends Record<string, any>> {
156
160
157
161
private logError ( e : unknown , errorMsg ?: string ) {
158
162
errorMsg && this . logger ?. error ( errorMsg , e instanceof Error ? e : undefined )
159
- return undefined
160
163
}
161
164
162
165
/**
163
166
* run in transaction, support nest call (using savepoint)
164
167
*/
165
168
public async transaction < O > (
166
169
fn : ( trx : Transaction < DB > ) => Promise < O > ,
167
- options : TransactionOptions = { } ,
170
+ options : TransactionOptions < O > = { } ,
168
171
) : Promise < O | undefined > {
169
172
if ( ! this . trx ) {
170
173
return await this . kysely . transaction ( )
@@ -174,20 +177,29 @@ export class SqliteBuilder<DB extends Record<string, any>> {
174
177
return await fn ( trx )
175
178
} )
176
179
. then ( async ( result ) => {
177
- await options . afterCommit ?.( )
180
+ await options . afterCommit ?.( result )
178
181
return result
179
182
} )
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
+ } )
181
188
. finally ( ( ) => this . trx = undefined )
182
189
}
190
+
183
191
this . trxCount ++
184
192
this . logger ?. debug ( `run in savepoint: sp_${ this . trxCount } ` )
185
193
return await runWithSavePoint ( this . trx ! , fn , `sp_${ this . trxCount } ` )
186
194
. then ( async ( result ) => {
187
- await options . afterCommit ?.( )
195
+ await options . afterCommit ?.( result )
188
196
return result
189
197
} )
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
+ } )
191
203
. finally ( ( ) => this . trxCount -- )
192
204
}
193
205
0 commit comments