You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.8 KiB

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