2021-06-03 03:36:25 +00:00
|
|
|
import {Connection} from './connection/Connection'
|
|
|
|
import {Inject, Singleton} from '../di'
|
|
|
|
import {ErrorWithContext, uuid4} from '../util'
|
|
|
|
import {AppClass} from '../lifecycle/AppClass'
|
|
|
|
import {Logging} from '../service/Logging'
|
2021-06-02 01:59:40 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* A singleton, non-unit service that stores and retrieves database connections by name.
|
|
|
|
*/
|
|
|
|
@Singleton()
|
|
|
|
export class DatabaseService extends AppClass {
|
|
|
|
@Inject()
|
|
|
|
protected logging!: Logging
|
|
|
|
|
|
|
|
/** Mapping of connection name -> connection instance for connections registered with this service. */
|
|
|
|
protected readonly connections: { [key: string]: Connection } = {}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Register a new connection instance by name.
|
|
|
|
* @param name
|
|
|
|
* @param connection
|
|
|
|
*/
|
2021-06-03 03:36:25 +00:00
|
|
|
register(name: string, connection: Connection): this {
|
2021-06-02 01:59:40 +00:00
|
|
|
if ( this.connections[name] ) {
|
|
|
|
this.logging.warn(`Overriding duplicate connection: ${name}`)
|
|
|
|
}
|
|
|
|
|
|
|
|
this.connections[name] = connection
|
2021-06-03 03:36:25 +00:00
|
|
|
return this
|
2021-06-02 01:59:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns true if a connection is registered with the given name.
|
|
|
|
* @param name
|
|
|
|
*/
|
2021-06-03 03:36:25 +00:00
|
|
|
has(name: string): boolean {
|
|
|
|
return Boolean(this.connections[name])
|
2021-06-02 01:59:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get a connection instance by its name. Throws if none exists.
|
|
|
|
* @param name
|
|
|
|
*/
|
2021-07-25 14:15:01 +00:00
|
|
|
get(name = 'default'): Connection {
|
2021-06-02 01:59:40 +00:00
|
|
|
if ( !this.has(name) ) {
|
|
|
|
throw new ErrorWithContext(`No such connection is registered: ${name}`)
|
|
|
|
}
|
|
|
|
|
|
|
|
return this.connections[name]
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return an array of the names of all registered connections.
|
|
|
|
*/
|
|
|
|
names(): string[] {
|
|
|
|
return Object.keys(this.connections)
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Get a guaranteed-unique connection name. */
|
|
|
|
uniqueName(): string {
|
2021-06-03 03:36:25 +00:00
|
|
|
let name: string
|
2021-06-02 01:59:40 +00:00
|
|
|
|
|
|
|
do {
|
2021-06-03 03:36:25 +00:00
|
|
|
name = uuid4()
|
2021-06-02 01:59:40 +00:00
|
|
|
} while (this.has(name))
|
|
|
|
|
|
|
|
return name
|
|
|
|
}
|
|
|
|
}
|