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' /** * 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): this { if ( this.connections[name] ) { this.logging.warn(`Overriding duplicate connection: ${name}`) } this.connections[name] = connection return this } /** * Returns true if a connection is registered with the given name. * @param name */ has(name: string): boolean { return Boolean(this.connections[name]) } /** * Get a connection instance by its name. Throws if none exists. * @param name */ get(name = 'default'): 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 = uuid4() } while (this.has(name)) return name } }