Skip to content

Commit

Permalink
[#6] migration setting - ormconfig dynamic generate
Browse files Browse the repository at this point in the history
  • Loading branch information
le2sky committed Mar 8, 2022
1 parent 3ac1f96 commit d0963b9
Show file tree
Hide file tree
Showing 11 changed files with 68 additions and 20 deletions.
2 changes: 2 additions & 0 deletions docker/docker-compose.dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ services:
TZ: Asia/Seoul
ports:
- 5432:5432
volumes:
- db_data:/var/lib/postgresql/data
networks:
- oleunaelim

Expand Down
Empty file added ormconfig.json
Empty file.
1 change: 0 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
"test:e2e": "jest --config ./test/jest-e2e.json",
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js"
},
"dependencies": {
"@nestjs/common": "^8.0.0",
Expand All @@ -31,7 +32,6 @@
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",
"cross-env": "^7.0.3",
"dotenv": "^16.0.0",
"express-basic-auth": "^1.2.1",
"firebase-admin": "^10.0.1",
"joi": "^17.6.0",
Expand Down
16 changes: 1 addition & 15 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,7 @@ import { MountainModule } from './mountain/mountain.module';
isGlobal: true,
validationSchema,
}),
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (configService: ConfigService): TypeOrmModuleOptions => {
return {
type: 'postgres',
host: configService.get('DB_HOST'),
port: configService.get<number>('DB_PORT'),
username: configService.get('DB_USERNAME'),
password: configService.get('DB_USER_PASSWORD'),
database: configService.get('DATABASE_NAME'),
synchronize: process.env.NODE_ENV === 'production' ? false : true,
entities: ['dist/**/*.entity{.ts,.js}'],
};
},
}),
TypeOrmModule.forRoot(),
UserModule,
PostModule,
MountainModule,
Expand Down
41 changes: 41 additions & 0 deletions src/config/config.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { TypeOrmModuleOptions } from '@nestjs/typeorm';

require('dotenv').config();

export class ConfigService {
constructor(private env: { [k: string]: string | undefined }) {}

private getValue(key: string, throwOnMissing = true): string {
const value = this.env[key];
if (!value && throwOnMissing) {
throw new Error(`config error - missing env.${key}`);
}

return value;
}

isLocal(): boolean {
return this.getValue('NODE_ENV', false) === 'local';
}
getTypeOrmConfig(): TypeOrmModuleOptions {
const tempPort = Number(this.getValue('DB_PORT'));
const join = require('path').join;
return {
type: 'postgres',
host: this.getValue('DB_HOST'),
port: isNaN(tempPort) ? 5432 : tempPort,
username: this.getValue('DB_USERNAME'),
password: this.getValue('DB_USER_PASSWORD'),
database: this.getValue('DATABASE_NAME'),
synchronize: this.isLocal() ? true : false,
entities: ['dist/**/*.entity{.ts,.js}'],
migrations: [
this.isLocal() ? join(__dirname, '/migrations/*{.ts,.js}') : join(__dirname, '../dist/migrations/*{.ts,.js}'),
],
cli: {
entitiesDir: join(__dirname, 'database', 'entities'),
migrationsDir: join(__dirname, 'migrations'),
},
};
}
}
File renamed without changes.
File renamed without changes.
12 changes: 12 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,17 @@ import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { Logger, ValidationPipe } from '@nestjs/common';
import { HttpExceptionFilter } from './common/exceptions/http-exception.filter';
import { AppModule } from './app.module';
import { ConfigService } from './config/config.service';
import * as fs from 'fs';

async function makeOrmConfig() {
const configService = new ConfigService(process.env);
const typeormConfig = configService.getTypeOrmConfig();
if (fs.existsSync('ormconfig.json')) {
fs.unlinkSync('ormconfig.json');
}
fs.writeFileSync('ormconfig.json', JSON.stringify(typeormConfig, null, 2));
}

class Application {
private PORT: string;
Expand Down Expand Up @@ -90,6 +101,7 @@ class Application {
}

async function init() {
await makeOrmConfig();
const server = await NestFactory.create<NestExpressApplication>(AppModule);
const app = new Application(server);
try {
Expand Down
11 changes: 9 additions & 2 deletions src/mountain/mountain.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,20 @@ export interface IMountainInforamtion {

@Injectable()
export class MountainHelper implements OnModuleInit {
constructor(@InjectRepository(MountainsEntity) private readonly mountainRepository: Repository<MountainsEntity>) {}
randomImage: () => Promise<string>;
async onModuleInit() {
if (!(await this.isDataBinding())) {
Logger.log('DB์— ์‚ฐ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ์ €์žฅ์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.', 'MountainHelper');
await this.seedingData();
}
}
constructor(@InjectRepository(MountainsEntity) private readonly mountainRepository: Repository<MountainsEntity>) {
this.randomImage = require('../lib/mountain-random-image/main');
}
async getMountainImage(): Promise<string> {
const imageUrl: string = await this.randomImage();
return imageUrl;
}

private async isDataBinding(): Promise<boolean> {
const mountains = await this.mountainRepository.createQueryBuilder('mountains').limit(100).getMany();
Expand Down Expand Up @@ -47,7 +54,7 @@ export class MountainHelper implements OnModuleInit {
} catch (err) {
Logger.log('JSON ๋ฐ์ดํ„ฐ๋ฅผ ์ฝ๋Š”๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.', 'MountainHelper');
Logger.log('JSON ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ต๋‹ˆ๋‹ค.', 'MountainHelper');
const mountainsGenerator = require('../lib/mountain-generator/index');
const mountainsGenerator = require('../lib/mountain-generator/main');
await mountainsGenerator();
await this.seedingData();
}
Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"allowJs": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
Expand Down

0 comments on commit d0963b9

Please sign in to comment.