import 'reflect-metadata';
import { Connection, createConnection } from 'typeorm';
import { throwError } from './error';

export enum Databases {
  LIBRARY = 'library',
}

const connections: {
  [key in Databases]?: Connection;
} = {};

Object.values(Databases).forEach((database: Databases) => {
  createConnection(database)
    .then((connection: Connection) => {
      connections[database] = connection;
      return connection.runMigrations();
    })
    .catch((reason: any) => {
      throwError(reason, true);
    });
});

export function getConnection(database: Databases): Promise<Connection> {
  if (connections[database] === undefined) {
    return createConnection(database).then((connection: Connection) => {
      connections[database] = connection;
      return connection;
    });
  } else {
    return Promise.resolve(connections[database]);
  }
}
