Skip to content

Commit a7bc62d

Browse files
committed
feat: Implement ServiceProvider for centralized database access and service management
- Created the `ServiceProvider` class to provide centralized access to the `Client`, `ConnectionPool`, `GroupService`, and `UserService`. - Ensured that the `ServiceProvider` follows the singleton pattern, initializing only once and reusing the instance. - Added methods to retrieve the `Client`, `ConnectionPool`, and services for managing groups and users (`GroupService` and `UserService`). - Implemented `getPoolClint` method for acquiring a connection client from the connection pool. - Included `close` method to close the connection pool when no longer needed. - Added initialization logic in `initialize` method to ensure proper setup and avoid multiple initializations. This update centralizes database management and service instantiation, simplifying access to core functionalities.
1 parent 472a2c6 commit a7bc62d

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { PoolClient } from 'pg';
2+
import { Client } from '../../database/Client';
3+
import { ConnectionPool } from '../../database/ConnectionPool';
4+
import { GroupService } from '../../database/service/group/Group';
5+
import { UserService } from '../../database/service/user/User';
6+
7+
export class ServiceProvider {
8+
private static instance: ServiceProvider;
9+
private _clientInstance: Client;
10+
private _connectionPool!: ConnectionPool;
11+
private constructor() {
12+
this._clientInstance = new Client();
13+
}
14+
15+
static async initialize(): Promise<ServiceProvider> {
16+
if (!ServiceProvider.instance) {
17+
const instance = new ServiceProvider();
18+
await instance._clientInstance.initialize();
19+
instance._connectionPool = instance._clientInstance.getConnectionPool();
20+
ServiceProvider.instance = instance;
21+
}
22+
return ServiceProvider.instance;
23+
}
24+
static getInstance() {
25+
return ServiceProvider.instance;
26+
}
27+
getClient(): Client {
28+
return this._clientInstance;
29+
}
30+
31+
getConnectionPool(): ConnectionPool {
32+
return this._connectionPool;
33+
}
34+
async close(): Promise<void> {
35+
await this._connectionPool.close();
36+
}
37+
async getPoolClint(): Promise<PoolClient> {
38+
return await this._connectionPool.getClient();
39+
}
40+
async getGroupService() {
41+
const clint = await this.getPoolClint();
42+
return new GroupService(clint);
43+
}
44+
async getUserService() {
45+
const clint = await this.getPoolClint();
46+
return new UserService(clint);
47+
}
48+
}

0 commit comments

Comments
 (0)