@@ -5,6 +5,7 @@ import { GroupService } from '../../database/models/Group';
5
5
import { UserService } from '../../database/models/User' ;
6
6
import { GroupRuleService } from '../../database/models/GroupRule' ;
7
7
import { WarningDatabaseService } from '../../database/models/Warning' ;
8
+ import logger from '../../utils/logger' ;
8
9
9
10
export class ServiceProvider {
10
11
private static instance : ServiceProvider ;
@@ -40,20 +41,28 @@ export class ServiceProvider {
40
41
return await this . _connectionPool . getClient ( ) ;
41
42
}
42
43
async getGroupService ( ) {
43
- const client = await this . getPoolClint ( ) ;
44
- return new GroupService ( client ) ;
44
+ return await this . retryConnect ( async ( ) => {
45
+ const client = await this . getPoolClint ( ) ;
46
+ return new GroupService ( client ) ;
47
+ } ) ;
45
48
}
46
49
async getUserService ( ) {
47
- const client = await this . getPoolClint ( ) ;
48
- return new UserService ( client ) ;
50
+ return await this . retryConnect ( async ( ) => {
51
+ const client = await this . getPoolClint ( ) ;
52
+ return new UserService ( client ) ;
53
+ } ) ;
49
54
}
50
55
async getRulesService ( ) {
51
- const client = await this . getPoolClint ( ) ;
52
- return new GroupRuleService ( client ) ;
56
+ return await this . retryConnect ( async ( ) => {
57
+ const client = await this . getPoolClint ( ) ;
58
+ return new GroupRuleService ( client ) ;
59
+ } ) ;
53
60
}
54
61
async getWarnsService ( ) {
55
- const clint = await this . getPoolClint ( ) ;
56
- return new WarningDatabaseService ( clint ) ;
62
+ return await this . retryConnect ( async ( ) => {
63
+ const clint = await this . getPoolClint ( ) ;
64
+ return new WarningDatabaseService ( clint ) ;
65
+ } ) ;
57
66
}
58
67
async healthCheck ( ) : Promise < boolean > {
59
68
try {
@@ -67,4 +76,17 @@ export class ServiceProvider {
67
76
return false ;
68
77
}
69
78
}
79
+ private async retryConnect ( fn : Function , retries = 3 , delay = 5000 ) {
80
+ for ( let attempt = 0 ; attempt < retries ; attempt ++ ) {
81
+ try {
82
+ return await fn ( ) ;
83
+ } catch ( error : any ) {
84
+ logger . error ( `Database Retry Attempt ${ attempt + 1 } : ${ error . message } ` , 'Database' ) ;
85
+ if ( attempt < retries - 1 ) {
86
+ await new Promise ( ( res ) => setTimeout ( res , delay ) ) ;
87
+ }
88
+ }
89
+ }
90
+ throw new Error ( 'Failed to connect to the database after retries' ) ;
91
+ }
70
92
}
0 commit comments