File tree 2 files changed +56
-0
lines changed
2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ import {
2
+ CallHandler ,
3
+ ExecutionContext ,
4
+ Injectable ,
5
+ NestInterceptor ,
6
+ } from '@nestjs/common' ;
7
+ import {
8
+ catchError ,
9
+ finalize ,
10
+ Observable ,
11
+ concatMap ,
12
+ } from 'rxjs' ;
13
+ import { QueryRunner , DataSource } from 'typeorm' ;
14
+
15
+ @Injectable ( )
16
+ export class TransactionInterceptor implements NestInterceptor {
17
+ constructor ( private readonly dataSource : DataSource ) { }
18
+
19
+ async intercept (
20
+ context : ExecutionContext ,
21
+ next : CallHandler < any > ,
22
+ ) : Promise < Observable < any > > {
23
+ const request = context . switchToHttp ( ) . getRequest ( ) ;
24
+ const queryRunner : QueryRunner = await this . initRunner ( ) ;
25
+ request . queryRunnerManager = queryRunner . manager ;
26
+
27
+ return next . handle ( ) . pipe (
28
+ concatMap ( async ( data ) => {
29
+ await queryRunner . commitTransaction ( ) ;
30
+ return data ;
31
+ } ) ,
32
+ catchError ( async ( error ) => {
33
+ await queryRunner . rollbackTransaction ( ) ;
34
+ throw error ;
35
+ } ) ,
36
+ finalize ( async ( ) => {
37
+ await queryRunner . release ( ) ;
38
+ } ) ,
39
+ ) ;
40
+ }
41
+
42
+ private async initRunner ( ) : Promise < QueryRunner > {
43
+ const queryRunner : QueryRunner = this . dataSource . createQueryRunner ( ) ;
44
+ await queryRunner . connect ( ) ;
45
+ await queryRunner . startTransaction ( ) ;
46
+ return queryRunner ;
47
+ }
48
+ }
Original file line number Diff line number Diff line change
1
+ import { ExecutionContext , createParamDecorator } from "@nestjs/common" ;
2
+
3
+ export const TransactionManager = createParamDecorator (
4
+ ( data : unknown , ctx : ExecutionContext ) => {
5
+ const request = ctx . switchToHttp ( ) . getRequest ( ) ;
6
+ return request . queryRunnerManager ;
7
+ }
8
+ )
You can’t perform that action at this time.
0 commit comments