feat: run typeorm database migrations on app start

This commit is contained in:
Xymorot 2019-10-03 02:09:45 +02:00
parent f334b68108
commit 03026f1cdd
2 changed files with 14 additions and 3 deletions

View File

@ -10,7 +10,6 @@
- `npm run rebuild`
- might need to install some build tools depending on your platform
- `npm run watch` for code transpilation (starts watchers)
- `npm run typeorm:migrate` for creating/migrating the database
- `npm run start`
### Git Commits
@ -30,7 +29,7 @@ Always try to split up your changes into coherent commits, a single commit shoul
### Database Migrations
Migrations are stored in [src/main/migrations](src/main/migrations) and handled by typeorm.
Migrations are stored in [src/main/migrations](src/main/migrations) and handled by typeorm. Migrations are run on app start inside [database.ts](src/main/services/database.ts).
To auto-generate a migration:
`node_modules/.bin/typeorm migration:generate -n <migration name> -c <connection name>`

View File

@ -1,7 +1,8 @@
import 'reflect-metadata';
import { Connection, createConnection } from 'typeorm';
import { throwError } from './error';
export const enum Databases {
export enum Databases {
LIBRARY = 'library',
}
@ -9,6 +10,17 @@ 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);
});
});
export function getConnection(database: Databases): Promise<Connection> {
if (connections[database] === undefined) {
return createConnection(database).then((connection: Connection) => {