66 lines
2.0 KiB
TypeScript
66 lines
2.0 KiB
TypeScript
import path from 'path';
|
|
import { Connection, createConnection as ormCreateConnection, EntityManager, EntityTarget, Repository } from 'typeorm';
|
|
import type { BetterSqlite3ConnectionOptions } from 'typeorm/driver/better-sqlite3/BetterSqlite3ConnectionOptions';
|
|
import { appPath } from './app-path';
|
|
|
|
export enum Database {
|
|
LIBRARY = 'library',
|
|
STORE = 'store',
|
|
}
|
|
|
|
type MyConnectionOptions = { [key in Database]: BetterSqlite3ConnectionOptions };
|
|
|
|
const databaseDir = path.resolve(appPath, 'database');
|
|
|
|
/**
|
|
* @see ormconfig.yml in the root folder
|
|
*/
|
|
function getConnectionOptionsFor(database: Database): BetterSqlite3ConnectionOptions {
|
|
return {
|
|
name: database,
|
|
type: 'better-sqlite3',
|
|
database: path.resolve(databaseDir, `${database}.db`),
|
|
cache: true,
|
|
entities: [`./src/main/entities/${database}/*.js`],
|
|
migrations: [`./src/main/migrations/${database}/*.js`],
|
|
cli: {
|
|
migrationsDir: `./src/main/migrations/${database}`,
|
|
},
|
|
};
|
|
}
|
|
|
|
const connectionOptions: MyConnectionOptions = {
|
|
[Database.LIBRARY]: getConnectionOptionsFor(Database.LIBRARY),
|
|
[Database.STORE]: getConnectionOptionsFor(Database.STORE),
|
|
};
|
|
|
|
function createConnection(database: Database): Promise<Connection> {
|
|
let connection: Connection;
|
|
return ormCreateConnection(connectionOptions[database])
|
|
.then((c) => {
|
|
connection = c;
|
|
return c.runMigrations();
|
|
})
|
|
.then(() => connection);
|
|
}
|
|
|
|
const connections = {
|
|
[Database.LIBRARY]: createConnection(Database.LIBRARY),
|
|
[Database.STORE]: createConnection(Database.STORE),
|
|
};
|
|
|
|
export function getConnection(database: Database): Promise<Connection> {
|
|
return connections[database];
|
|
}
|
|
|
|
export function getManager(database: Database): Promise<EntityManager> {
|
|
return getConnection(database).then((c) => c.manager);
|
|
}
|
|
|
|
export function getRepository<T>(
|
|
target: EntityTarget<T>,
|
|
database: Database = Database.LIBRARY,
|
|
): Promise<Repository<T>> {
|
|
return getManager(database).then((m) => m.getRepository(target));
|
|
}
|