Skip to content

Commit

Permalink
Merge pull request #164 from AthennaIO/develop
Browse files Browse the repository at this point in the history
chore(npm): update dependencies
  • Loading branch information
jlenon7 authored May 17, 2024
2 parents 705fcbd + d015dbc commit f6427c6
Show file tree
Hide file tree
Showing 26 changed files with 525 additions and 844 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@athenna/database",
"version": "4.53.0",
"version": "4.54.0",
"description": "The Athenna database handler for SQL/NoSQL.",
"license": "MIT",
"author": "João Lenon <lenon@athenna.io>",
Expand Down
18 changes: 12 additions & 6 deletions src/database/DatabaseImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

import type { Knex } from 'knex'
import { Path, Module, Options } from '@athenna/common'
import { DriverFactory } from '#src/factories/DriverFactory'
import type { Connections, ConnectionOptions } from '#src/types'
import type { FakeDriver } from '#src/database/drivers/FakeDriver'
import { QueryBuilder } from '#src/database/builders/QueryBuilder'
Expand All @@ -36,7 +35,7 @@ export class DatabaseImpl<Driver extends DriverImpl = any> {
* Creates a new instance of DatabaseImpl.
*/
public constructor(athennaDbOpts?: ConnectionOptions) {
this.driver = DriverFactory.fabricate(
this.driver = ConnectionFactory.fabricate(
this.connectionName
) as unknown as Driver

Expand Down Expand Up @@ -69,7 +68,7 @@ export class DatabaseImpl<Driver extends DriverImpl = any> {
): DatabaseImpl<typeof FakeDriver>

public connection(
con: Connections,
con: 'mongo' | 'mysql' | 'sqlite' | 'postgres' | 'fake' | string,
options?: ConnectionOptions
):
| DatabaseImpl<MongoDriver>
Expand All @@ -82,7 +81,7 @@ export class DatabaseImpl<Driver extends DriverImpl = any> {
* Change the database connection.
*/
public connection(con: Connections, options?: ConnectionOptions) {
const driver = DriverFactory.fabricate(con)
const driver = ConnectionFactory.fabricate(con)
const database = new DatabaseImpl<typeof driver>(options)

database.connectionName = con
Expand Down Expand Up @@ -118,7 +117,14 @@ export class DatabaseImpl<Driver extends DriverImpl = any> {
* Close all the connections with all databases.
*/
public async closeAll(): Promise<void> {
await ConnectionFactory.closeAllConnections()
const cons = ConnectionFactory.availableConnections()
const promises = cons.map(con => {
const driver = ConnectionFactory.fabricate(con)

return driver.close().then(() => ConnectionFactory.setClient(con, null))
})

await Promise.all(promises)
}

/**
Expand All @@ -143,7 +149,7 @@ export class DatabaseImpl<Driver extends DriverImpl = any> {
}

/**
* Run datase seeders.
* Run database seeders.
*/
public async runSeeders(
options: {
Expand Down
38 changes: 32 additions & 6 deletions src/database/drivers/Driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,18 @@
* file that was distributed with this source code.
*/

import type { Knex, TableBuilder } from 'knex'
import type { ModelSchema } from '#src/models/schemas/ModelSchema'
import type { Transaction } from '#src/database/transactions/Transaction'
import type { Direction, ConnectionOptions, Operations } from '#src/types'
import { NotFoundDataException } from '#src/exceptions/NotFoundDataException'
import {
Collection,
Module,
Options,
Collection,
type PaginatedResponse,
type PaginationOptions
} from '@athenna/common'
import type { Knex, TableBuilder } from 'knex'
import type { ModelSchema } from '#src/models/schemas/ModelSchema'
import type { Transaction } from '#src/database/transactions/Transaction'
import type { Direction, ConnectionOptions, Operations } from '#src/types'
import { NotFoundDataException } from '#src/exceptions/NotFoundDataException'

export abstract class Driver<Client = any, QB = any> {
/**
Expand Down Expand Up @@ -70,9 +71,34 @@ export abstract class Driver<Client = any, QB = any> {
if (client) {
this.client = client
this.isConnected = true
this.isSavedOnFactory = true
}
}

/**
* Import knex in a method to be easier to mock.
*/
public getKnex() {
const require = Module.createRequire(import.meta.url)

return require('knex')
}

/**
* Import mongoose in a method to be easier to mock.
*/
public getMongoose() {
const require = Module.createRequire(import.meta.url)

let mongoose = require('mongoose')

if (!mongoose.createConnection) {
mongoose = mongoose.default
}

return mongoose
}

/**
* Clone the driver instance.
*/
Expand Down
6 changes: 6 additions & 0 deletions src/database/drivers/FakeDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
Options,
type PaginatedResponse
} from '@athenna/common'

import type { ConnectionOptions, Operations } from '#src/types'
import { Transaction } from '#src/database/transactions/Transaction'
import { WrongMethodException } from '#src/exceptions/WrongMethodException'
Expand All @@ -28,6 +29,7 @@ export class FakeDriver {
if (client) {
FakeDriver.client = client
FakeDriver.isConnected = true
FakeDriver.isSavedOnFactory = true
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
Expand All @@ -50,6 +52,10 @@ export class FakeDriver {
return this
}

public static getKnex() {}

public static getMongoose() {}

public static clone() {
return Json.copy(FakeDriver)
}
Expand Down
43 changes: 33 additions & 10 deletions src/database/drivers/MongoDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import {
} from '@athenna/common'

import { debug } from '#src/debug'
import { Log } from '@athenna/logger'
import { Driver } from '#src/database/drivers/Driver'
import { DriverFactory } from '#src/factories/DriverFactory'
import { ModelSchema } from '#src/models/schemas/ModelSchema'
import { Transaction } from '#src/database/transactions/Transaction'
import { ConnectionFactory } from '#src/factories/ConnectionFactory'
Expand Down Expand Up @@ -75,15 +75,41 @@ export class MongoDriver extends Driver<Connection, Collection> {
return
}

this.client = ConnectionFactory.mongo(this.connection)
const mongoose = this.getMongoose()
const configs = Config.get(`database.connections.${this.connection}`, {})

if (options.saveOnFactory) {
DriverFactory.setClient('mongo', this.client)
if (configs.debug !== undefined) {
mongoose.set('debug', configs.debug)
}

const mongoOpts = Json.omit(configs, [
'url',
'debug',
'driver',
'validations'
])

debug('creating new connection using mongoose. options defined: %o', {
url: configs.url,
debug: configs.debug,
...mongoOpts
})

this.client = mongoose.createConnection(configs.url, mongoOpts)

if (Config.is('rc.bootLogs', true)) {
Log.channelOrVanilla('application').success(
`Successfully connected to ({yellow} ${this.connection}) database connection`
)
}

this.isConnected = true
this.isSavedOnFactory = options.saveOnFactory

if (this.isSavedOnFactory) {
ConnectionFactory.setClient(this.connection, this.client)
}

this.qb = this.query()
}

Expand All @@ -95,18 +121,15 @@ export class MongoDriver extends Driver<Connection, Collection> {
return
}

if (this.isSavedOnFactory && DriverFactory.hasClient('mongo')) {
await DriverFactory.getClient('mongo').close()
DriverFactory.setClient('mongo', null)
} else {
await this.client.close()
}
await this.client.close()

this.qb = null
this.tableName = null
this.client = null
this.session = null
this.isConnected = false

ConnectionFactory.setClient(this.connection, null)
}

/**
Expand Down
60 changes: 42 additions & 18 deletions src/database/drivers/MySqlDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,26 @@
* file that was distributed with this source code.
*/

import {
Exec,
Is,
Json,
Options,
type PaginatedResponse,
type PaginationOptions
} from '@athenna/common'

import type { Knex } from 'knex'
import { debug } from '#src/debug'
import { Log } from '@athenna/logger'
import { Driver } from '#src/database/drivers/Driver'
import { DriverFactory } from '#src/factories/DriverFactory'
import { Transaction } from '#src/database/transactions/Transaction'
import { ConnectionFactory } from '#src/factories/ConnectionFactory'
import { Transaction } from '#src/database/transactions/Transaction'
import type { ConnectionOptions, Direction, Operations } from '#src/types'
import { MigrationSource } from '#src/database/migrations/MigrationSource'
import { WrongMethodException } from '#src/exceptions/WrongMethodException'
import { PROTECTED_QUERY_METHODS } from '#src/constants/ProtectedQueryMethods'
import { NotConnectedDatabaseException } from '#src/exceptions/NotConnectedDatabaseException'
import {
Exec,
Is,
Options,
type PaginatedResponse,
type PaginationOptions
} from '@athenna/common'

export class MySqlDriver extends Driver<Knex, Knex.QueryBuilder> {
/**
Expand All @@ -46,15 +48,40 @@ export class MySqlDriver extends Driver<Knex, Knex.QueryBuilder> {
return
}

this.client = ConnectionFactory.mysql(this.connection)
const knex = this.getKnex()
const configs = Config.get(`database.connections.${this.connection}`, {})
const knexOpts = {
client: 'mysql2',
migrations: {
tableName: 'migrations'
},
pool: {
min: 2,
max: 20,
acquireTimeoutMillis: 60 * 1000
},
debug: false,
useNullAsDefault: false,
...Json.omit(configs, ['driver', 'validations'])
}

debug('creating new connection using Knex. options defined: %o', knexOpts)

if (options.saveOnFactory) {
DriverFactory.setClient('mysql', this.client)
if (Config.is('rc.bootLogs', true)) {
Log.channelOrVanilla('application').success(
`Successfully connected to ({yellow} ${this.connection}) database connection`
)
}

this.client = knex.default(knexOpts)

this.isConnected = true
this.isSavedOnFactory = options.saveOnFactory

if (this.isSavedOnFactory) {
ConnectionFactory.setClient(this.connection, this.client)
}

this.qb = this.query()
}

Expand All @@ -66,17 +93,14 @@ export class MySqlDriver extends Driver<Knex, Knex.QueryBuilder> {
return
}

if (this.isSavedOnFactory && DriverFactory.hasClient('mysql')) {
await DriverFactory.getClient('mysql').destroy()
DriverFactory.setClient('mysql', null)
} else {
await this.client.destroy()
}
await this.client.destroy()

this.qb = null
this.tableName = null
this.client = null
this.isConnected = false

ConnectionFactory.setClient(this.connection, null)
}

/**
Expand Down
Loading

0 comments on commit f6427c6

Please sign in to comment.