daton/orm/src/service/Database.ts

64 lines
1.8 KiB
TypeScript
Raw Normal View History

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
*/
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
*/
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.
*/
@Service()
export default class Database {
2020-08-17 14:44:23 +00:00
/**
* The created connections, keyed by name.
* @type object
*/
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>
*/
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
*/
connection(name: string): Connection {
if ( !this.connections[name] )
throw new NoSuchDatabaseConnectionError(name)
return this.connections[name]
}
}