feat(cli): create DB in start command if not exists (#285)

This commit is contained in:
Ali BARIN
2022-04-08 11:36:35 +02:00
committed by GitHub
parent 75eda7f2af
commit c227dc86bb
19 changed files with 211 additions and 126 deletions

View File

@@ -1,3 +1,4 @@
import { readFileSync } from 'fs';
import { Command, Flags } from '@oclif/core';
import * as dotenv from 'dotenv';
@@ -16,7 +17,13 @@ export default class Start extends Command {
const { flags } = await this.parse(Start);
if (flags['env-file']) {
dotenv.config({ path: flags['env-file'] });
const envFile = readFileSync(flags['env-file'], 'utf8');
const envConfig = dotenv.parse(envFile);
for (const key in envConfig) {
const value = envConfig[key];
process.env[key] = value;
}
}
if (flags.env) {
@@ -26,31 +33,57 @@ export default class Start extends Command {
}
}
// must serve until more customization is introduced
delete process.env.SERVE_WEB_APP_SEPARATELY;
}
async createDatabaseAndUser(): Promise<void> {
const { utils } = await import('@automatisch/backend/database');
await utils.createDatabaseAndUser(
process.env.POSTGRES_DATABASE,
process.env.POSTGRES_USERNAME,
);
}
async runMigrationsIfNeeded(): Promise<void> {
const database = (await import('@automatisch/backend/dist/src/config/database')).default;
const migrator = database.migrate;
const { logger } = await import('@automatisch/backend/logger');
const { database } = await import('@automatisch/backend/database');
const migrator = database.client.migrate;
const [, pendingMigrations] = await migrator.list();
const pendingMigrationsCount = pendingMigrations.length;
const needsToMigrate = pendingMigrationsCount > 0;
if (needsToMigrate) {
logger.info(`Processing ${pendingMigrationsCount} migrations.`);
await migrator.latest();
logger.info(`Completed ${pendingMigrationsCount} migrations.`);
} else {
logger.info('No migrations needed.');
}
}
async seedUser(): Promise<void> {
const { utils } = await import('@automatisch/backend/database');
await utils.createUser();
}
async runApp(): Promise<void> {
await import('@automatisch/backend/dist/src/server');
await import('@automatisch/backend/server');
}
async run(): Promise<void> {
await this.prepareEnvVars();
await this.createDatabaseAndUser();
await this.runMigrationsIfNeeded();
await this.seedUser();
await this.runApp();
}
}

View File

@@ -11,7 +11,6 @@
"skipLibCheck": true,
"strict": true,
"target": "es2021",
"traceResolution": false,
"typeRoots": ["node_modules/@types", "./src/types"]
},
"include": ["src/**/*"]