2020-07-06 14:53:03 +00:00
|
|
|
import { Service } from '../../../di/src/decorator/Service.ts'
|
|
|
|
import { Connection } from '../db/Connection.ts'
|
|
|
|
import PostgresConnection from '../db/PostgresConnection.ts'
|
|
|
|
|
2020-08-17 14:44:23 +00:00
|
|
|
/**
|
|
|
|
* Error thrown if two connections with the same name are registered.
|
|
|
|
* @extends Error
|
|
|
|
*/
|
2020-07-06 14:53:03 +00:00
|
|
|
export class DuplicateConnectionNameError extends Error {
|
|
|
|
constructor(connection_name: string) {
|
|
|
|
super(`A database connection with the name "${connection_name}" already exists.`)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-17 14:44:23 +00:00
|
|
|
/**
|
|
|
|
* Error thrown if a connection name is accessed when there is no corresponding connection registered.
|
|
|
|
* @extends Error
|
|
|
|
*/
|
2020-07-06 14:53:03 +00:00
|
|
|
export class NoSuchDatabaseConnectionError extends Error {
|
|
|
|
constructor(connection_name: string) {
|
|
|
|
super(`No database connection exists with the name: "${connection_name}"`)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-17 14:44:23 +00:00
|
|
|
/**
|
|
|
|
* Service that manages and creates database connections.
|
|
|
|
*/
|
2020-07-06 14:53:03 +00:00
|
|
|
@Service()
|
|
|
|
export default class Database {
|
2020-08-17 14:44:23 +00:00
|
|
|
/**
|
|
|
|
* The created connections, keyed by name.
|
|
|
|
* @type object
|
|
|
|
*/
|
2020-07-06 14:53:03 +00:00
|
|
|
private connections: { [name: string]: Connection } = {}
|
|
|
|
|
2020-08-17 14:44:23 +00:00
|
|
|
/**
|
|
|
|
* Create a new PostgreSQL connection.
|
|
|
|
* @param {string} name
|
|
|
|
* @param {object} config
|
|
|
|
* @return Promise<PostgresConnection>
|
|
|
|
*/
|
2020-07-06 14:53:03 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2020-08-17 14:44:23 +00:00
|
|
|
/**
|
|
|
|
* Get a connection by name.
|
|
|
|
* @param name
|
|
|
|
* @return Connection
|
|
|
|
*/
|
2020-07-06 14:53:03 +00:00
|
|
|
connection(name: string): Connection {
|
|
|
|
if ( !this.connections[name] )
|
|
|
|
throw new NoSuchDatabaseConnectionError(name)
|
|
|
|
|
|
|
|
return this.connections[name]
|
|
|
|
}
|
|
|
|
}
|