Import other modules into monorepo
Some checks failed
continuous-integration/drone/push Build is failing
Some checks failed
continuous-integration/drone/push Build is failing
This commit is contained in:
68
src/orm/DatabaseService.ts
Normal file
68
src/orm/DatabaseService.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import {Connection} from "./connection/Connection";
|
||||
import {Inject, Singleton} from "../di";
|
||||
import {ErrorWithContext, uuid_v4} from "../util";
|
||||
import {AppClass} from "../lifecycle/AppClass";
|
||||
import {Logging} from "../service/Logging";
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
register(name: string, connection: Connection) {
|
||||
if ( this.connections[name] ) {
|
||||
this.logging.warn(`Overriding duplicate connection: ${name}`)
|
||||
}
|
||||
|
||||
this.connections[name] = connection
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a connection is registered with the given name.
|
||||
* @param name
|
||||
*/
|
||||
has(name: string) {
|
||||
return !!this.connections[name]
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a connection instance by its name. Throws if none exists.
|
||||
* @param name
|
||||
*/
|
||||
get(name: string): Connection {
|
||||
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 {
|
||||
let name: string;
|
||||
|
||||
do {
|
||||
name = uuid_v4()
|
||||
} while (this.has(name))
|
||||
|
||||
return name
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user