@@ -5,6 +5,7 @@ import { GroupService } from '../../database/models/Group';
55import { UserService } from '../../database/models/User' ;
66import { GroupRuleService } from '../../database/models/GroupRule' ;
77import { WarningDatabaseService } from '../../database/models/Warning' ;
8+ import logger from '../../utils/logger' ;
89
910export class ServiceProvider {
1011 private static instance : ServiceProvider ;
@@ -40,20 +41,28 @@ export class ServiceProvider {
4041 return await this . _connectionPool . getClient ( ) ;
4142 }
4243 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+ } ) ;
4548 }
4649 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+ } ) ;
4954 }
5055 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+ } ) ;
5360 }
5461 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+ } ) ;
5766 }
5867 async healthCheck ( ) : Promise < boolean > {
5968 try {
@@ -67,4 +76,17 @@ export class ServiceProvider {
6776 return false ;
6877 }
6978 }
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+ }
7092}
0 commit comments