38 lines
1.2 KiB
TypeScript
38 lines
1.2 KiB
TypeScript
|
import { Service } from '../../../di/src/decorator/Service.ts'
|
||
|
import { Connection } from '../db/Connection.ts'
|
||
|
import PostgresConnection from '../db/PostgresConnection.ts'
|
||
|
|
||
|
export class DuplicateConnectionNameError extends Error {
|
||
|
constructor(connection_name: string) {
|
||
|
super(`A database connection with the name "${connection_name}" already exists.`)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export class NoSuchDatabaseConnectionError extends Error {
|
||
|
constructor(connection_name: string) {
|
||
|
super(`No database connection exists with the name: "${connection_name}"`)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
@Service()
|
||
|
export default class Database {
|
||
|
private connections: { [name: string]: Connection } = {}
|
||
|
|
||
|
async postgres(name: string, config: { [key: string]: any }): Promise<PostgresConnection> {
|
||
|
if ( this.connections[name] )
|
||
|
throw new DuplicateConnectionNameError(name)
|
||
|
|
||
|
const conn = new PostgresConnection(name, config)
|
||
|
this.connections[name] = conn
|
||
|
await conn.init()
|
||
|
return conn
|
||
|
}
|
||
|
|
||
|
connection(name: string): Connection {
|
||
|
if ( !this.connections[name] )
|
||
|
throw new NoSuchDatabaseConnectionError(name)
|
||
|
|
||
|
return this.connections[name]
|
||
|
}
|
||
|
}
|