Skip to content

Commit 02026b4

Browse files
committed
refactor: create factories to handle drivers and connections
1 parent 1279802 commit 02026b4

15 files changed

Lines changed: 348 additions & 208 deletions

index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ export * from './src/Builders/ColumnBuilder'
1717
export * from './src/Builders/ReferenceColumnBuilder'
1818

1919
export * from './src/Utils/Transaction'
20-
export * from './src/Utils/ConnectionResolver'
20+
export * from './src/Utils/DriverFactory'
21+
export * from './src/Utils/ConnectionFactory'
2122

2223
export * from './src/Database'

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@secjs/database",
3-
"version": "1.0.1",
3+
"version": "1.0.2",
44
"description": "Handle your application database with factories, seeders and query builder in Node.js",
55
"license": "MIT",
66
"author": "João Lenon <lenon@secjs.com.br>",

src/Contracts/DatabaseContract.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ export interface DatabaseContract {
3232
* The most important method from drivers. Creates the connection with database
3333
*
3434
*/
35-
connect(): Promise<DatabaseContract>
35+
connect(force?: boolean, saveOnDriver?: boolean): Promise<DatabaseContract>
3636

3737
/**
3838
* On method
@@ -51,7 +51,7 @@ export interface DatabaseContract {
5151
* @return Return the actual database chain
5252
*
5353
*/
54-
clone(): Promise<DatabaseContract>
54+
clone(): DatabaseContract
5555

5656
/**
5757
* CloneQuery method

src/Contracts/DriverContract.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export interface DriverContract {
2020
* The most important method from drivers. Creates the connection with database
2121
*
2222
*/
23-
connect(): Promise<void>
23+
connect(force?: boolean, saveOnDriver?: boolean): Promise<void>
2424

2525
/**
2626
* On method

src/Database.ts

Lines changed: 33 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,10 @@
77
* file that was distributed with this source code.
88
*/
99

10-
import {
11-
InternalServerException,
12-
NotImplementedException,
13-
} from '@secjs/exceptions'
14-
15-
import { Drivers } from './Drivers/Drivers'
1610
import { JoinType } from './Contracts/JoinType'
17-
import { Config, PaginatedResponse, Path } from '@secjs/utils'
11+
import { DriverFactory } from './Utils/DriverFactory'
1812
import { DriverContract } from './Contracts/DriverContract'
13+
import { Config, PaginatedResponse, Path } from '@secjs/utils'
1914
import { DatabaseContract } from './Contracts/DatabaseContract'
2015
import { TransactionContract } from './Contracts/TransactionContract'
2116

@@ -24,71 +19,57 @@ export class Database implements DatabaseContract {
2419
private connectionName: string
2520
private driver: DriverContract
2621

27-
static build(
28-
name: string,
29-
driver: new (connection: string, configs?: any) => DriverContract,
30-
) {
31-
if (Drivers[name])
32-
throw new InternalServerException(`Driver ${name} already exists`)
22+
constructor(runtimeConfig: any = {}) {
23+
new Config().safeLoad(Path.config('database'))
3324

34-
Drivers[name] = driver
25+
this.runtimeConfig = runtimeConfig
26+
this.connectionName = 'default'
27+
this.driver = DriverFactory.fabricate('default', runtimeConfig)
3528
}
3629

3730
static get drivers(): string[] {
38-
return Object.keys(Drivers)
31+
return DriverFactory.availableDrivers()
3932
}
4033

41-
private createDriverInstance(connectionName?: string) {
42-
connectionName = connectionName || Config.get('database.default')
34+
static build(
35+
name: string,
36+
driver: new (connection: string, configs?: any) => DriverContract,
37+
) {
38+
DriverFactory.createDriver(name, driver)
39+
}
4340

44-
const connectionConfig = Config.get(
45-
`database.connections.${connectionName}`,
41+
static async closeDriver(...drivers: string[]): Promise<void> {
42+
const promises = drivers.map(driver =>
43+
DriverFactory.closeDriverConnection(driver),
4644
)
4745

48-
if (!connectionConfig) {
49-
throw new NotImplementedException(
50-
`Connection ${connectionName} is not configured inside database.connections object from config/database file`,
51-
)
52-
}
53-
54-
if (!Drivers[connectionConfig.driver]) {
55-
throw new NotImplementedException(
56-
`Driver ${connectionConfig.driver} does not exist, use Database.build method to create a new driver`,
57-
)
58-
}
59-
60-
this.connectionName = connectionName
61-
62-
return new Drivers[connectionConfig.driver](
63-
connectionName,
64-
this.runtimeConfig,
65-
)
46+
await Promise.all(promises)
6647
}
6748

68-
constructor(runtimeConfig: any = {}) {
69-
new Config().safeLoad(Path.config('database'))
70-
71-
this.runtimeConfig = runtimeConfig
72-
this.driver = this.createDriverInstance()
49+
static async closeAllDrivers(): Promise<void> {
50+
return DriverFactory.closeAllDriversConnection()
7351
}
7452

53+
// DriverContract Methods
54+
7555
connection(connection: string, runtimeConfig: any = {}): DatabaseContract {
7656
this.runtimeConfig = runtimeConfig
7757

78-
this.driver.close()
79-
this.driver = this.createDriverInstance(connection)
58+
this.connectionName = connection
59+
this.driver = DriverFactory.fabricate(connection, runtimeConfig)
8060

8161
return this
8262
}
8363

84-
// DriverContract Methods
85-
8664
setQueryBuilder(query: any): void {
8765
this.driver.setQueryBuilder(query)
8866
}
8967

90-
async connect(): Promise<DatabaseContract> {
91-
await this.driver.connect()
68+
async connect(
69+
force?: boolean,
70+
saveOnDriver?: boolean,
71+
): Promise<DatabaseContract> {
72+
await this.driver.connect(force, saveOnDriver)
9273

9374
return this
9475
}
@@ -101,10 +82,10 @@ export class Database implements DatabaseContract {
10182
return this.driver.cloneQuery()
10283
}
10384

104-
async clone(): Promise<DatabaseContract> {
105-
const database: any = await new Database()
106-
.connection(this.connectionName)
107-
.connect()
85+
clone(connection?: string): DatabaseContract {
86+
const database: any = new Database().connection(
87+
connection || this.connectionName,
88+
)
10889

10990
database.setQueryBuilder(this.cloneQuery())
11091

src/Drivers/Drivers.ts

Lines changed: 0 additions & 22 deletions
This file was deleted.

src/Drivers/MongoDriver.ts

Lines changed: 45 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,12 @@ import {
1515
Schema,
1616
} from 'mongoose'
1717
import { ObjectID } from 'bson'
18-
import { Is, paginate, PaginatedResponse } from '@secjs/utils'
1918
import { Transaction } from '../Utils/Transaction'
19+
import { DriverFactory } from '../Utils/DriverFactory'
2020
import { TableBuilder } from '../Builders/TableBuilder'
2121
import { InternalServerException } from '@secjs/exceptions'
2222
import { DriverContract } from '../Contracts/DriverContract'
23-
import { ConnectionResolver } from '../Utils/ConnectionResolver'
23+
import { Is, paginate, PaginatedResponse } from '@secjs/utils'
2424

2525
export class MongoDriver implements DriverContract {
2626
private defaultTable: string
@@ -33,27 +33,6 @@ export class MongoDriver implements DriverContract {
3333
private readonly configs: any
3434
private readonly connection: string
3535

36-
// This is important only for update and delete queries
37-
private _where = {}
38-
// This is important to be global in class to manipulate data before some operations
39-
private _pipeline = []
40-
41-
private get where() {
42-
const where = { ...this._where }
43-
44-
this._where = {}
45-
46-
return where
47-
}
48-
49-
private get pipeline() {
50-
const pipeline = [...this._pipeline]
51-
52-
this._pipeline = []
53-
54-
return pipeline
55-
}
56-
5736
constructor(
5837
client: any | string,
5938
configs: any = {},
@@ -74,6 +53,28 @@ export class MongoDriver implements DriverContract {
7453
this.isConnected = true
7554
}
7655

56+
// This is important only for update and delete queries
57+
private _where = {}
58+
59+
private get where() {
60+
const where = { ...this._where }
61+
62+
this._where = {}
63+
64+
return where
65+
}
66+
67+
// This is important to be global in class to manipulate data before some operations
68+
private _pipeline = []
69+
70+
private get pipeline() {
71+
const pipeline = [...this._pipeline]
72+
73+
this._pipeline = []
74+
75+
return pipeline
76+
}
77+
7778
async commit(): Promise<any | any[]> {
7879
const doc = await this.session.commitTransaction()
7980
await this.session.endSession()
@@ -94,12 +95,14 @@ export class MongoDriver implements DriverContract {
9495
return doc
9596
}
9697

97-
async connect(): Promise<void> {
98-
if (this.isConnected) return
98+
async connect(force = false, saveOnDriver = true): Promise<void> {
99+
if (this.isConnected && !force) return
99100

100-
this.client = await ConnectionResolver.mongoose(
101+
this.client = await DriverFactory.generateDriverClient(
102+
'mongo',
101103
this.connection,
102104
this.configs,
105+
saveOnDriver,
103106
)
104107

105108
this.isConnected = true
@@ -136,17 +139,27 @@ export class MongoDriver implements DriverContract {
136139
}
137140

138141
async createDatabase(databaseName: string): Promise<void> {
139-
const client = await ConnectionResolver.mongoose(this.connection, {
140-
database: databaseName,
141-
})
142+
const client = await DriverFactory.generateDriverClient(
143+
'mongo',
144+
this.connection,
145+
{
146+
database: databaseName,
147+
},
148+
false,
149+
)
142150

143151
await client.close()
144152
}
145153

146154
async dropDatabase(databaseName: string): Promise<void> {
147-
const client = await ConnectionResolver.mongoose(this.connection, {
148-
database: databaseName,
149-
})
155+
const client = await DriverFactory.generateDriverClient(
156+
'mongo',
157+
this.connection,
158+
{
159+
database: databaseName,
160+
},
161+
false,
162+
)
150163

151164
await client.dropDatabase()
152165
await client.close()

src/Drivers/MySqlDriver.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88
*/
99

1010
import { Knex } from 'knex'
11-
import { paginate, PaginatedResponse } from '@secjs/utils'
1211
import { Transaction } from '../Utils/Transaction'
12+
import { DriverFactory } from '../Utils/DriverFactory'
13+
import { paginate, PaginatedResponse } from '@secjs/utils'
1314
import { InternalServerException } from '@secjs/exceptions'
1415
import { DriverContract } from '../Contracts/DriverContract'
15-
import { ConnectionResolver } from '../Utils/ConnectionResolver'
1616

1717
export class MySqlDriver implements DriverContract {
1818
private isConnected: boolean
@@ -117,13 +117,14 @@ export class MySqlDriver implements DriverContract {
117117
this.queryBuilder.on(event, callback)
118118
}
119119

120-
async connect(): Promise<void> {
121-
if (this.isConnected) return
120+
async connect(force = false, saveOnDriver = true): Promise<void> {
121+
if (this.isConnected && !force) return
122122

123-
this.client = await ConnectionResolver.knex(
123+
this.client = await DriverFactory.generateDriverClient(
124124
'mysql',
125125
this.connection,
126126
this.configs,
127+
saveOnDriver,
127128
)
128129
this.queryBuilder = this.query()
129130

src/Drivers/PostgresDriver.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88
*/
99

1010
import { Knex } from 'knex'
11-
import { paginate, PaginatedResponse } from '@secjs/utils'
1211
import { Transaction } from '../Utils/Transaction'
12+
import { DriverFactory } from '../Utils/DriverFactory'
13+
import { Is, paginate, PaginatedResponse } from '@secjs/utils'
1314
import { InternalServerException } from '@secjs/exceptions'
1415
import { DriverContract } from '../Contracts/DriverContract'
15-
import { ConnectionResolver } from '../Utils/ConnectionResolver'
1616

1717
export class PostgresDriver implements DriverContract {
1818
private isConnected: boolean
@@ -25,7 +25,7 @@ export class PostgresDriver implements DriverContract {
2525
private readonly connection: string
2626

2727
constructor(client?: Knex | Knex.Transaction | string, configs?: any) {
28-
if (typeof client === 'string') {
28+
if (Is.String(client)) {
2929
this.isConnected = false
3030
this.defaultTable = null
3131

@@ -117,13 +117,14 @@ export class PostgresDriver implements DriverContract {
117117
this.queryBuilder.on(event, callback)
118118
}
119119

120-
async connect(): Promise<void> {
121-
if (this.isConnected) return
120+
async connect(force = false, saveOnDriver = true): Promise<void> {
121+
if (this.isConnected && !force) return
122122

123-
this.client = await ConnectionResolver.knex(
124-
'pg',
123+
this.client = await DriverFactory.generateDriverClient(
124+
'postgres',
125125
this.connection,
126126
this.configs,
127+
saveOnDriver,
127128
)
128129
this.queryBuilder = this.query()
129130

0 commit comments

Comments
 (0)