简体   繁体   中英

Migrations with async DataSource Typeorm+Nestjs

I was wondering if someone knows how to generate and run migrations using an async DataSource from TypeORM on a NestJS environment.

What I mean with async DataSource is that the values of the database connection are fetched on the fly (from a secret manager provider).

There is a PR with this information here but, what is the best practice to merge this "concept" into NestJS?. Do I need to create two separate DataSource configurations?, one for nest and one for the migrations?.

My proyect run the TypeOrmModule like this (and works as expected when starting nest):

TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => {
        await configService.setDBCredentials();
        return {
          type: TRANSACTIONAL_DATABASE_TYPE,
          host: configService.transactionalDatabaseCredentials.DATABASE_HOST,
          port: configService.transactionalDatabaseCredentials.DATABASE_PORT,
          username: configService.transactionalDatabaseCredentials.DATABASE_USER,
          password: configService.transactionalDatabaseCredentials.DATABASE_PASSWORD,
          database: configService.transactionalDatabaseCredentials.DATABASES_NAME,
          entities: [Member]
        }
      },
      inject: [ConfigService],
    }),

The Github link to the issue has been updated here , notably by DanielMaranhao. Personally, I still use 2 datasources (one for migrations and one for Nest configuration)

In addition to the configuration you show, I created this file named "data-source.ts" in my src/database folder

// src/database/data-source.ts

import * as dotenv from 'dotenv';
import * as dotenvExpand from 'dotenv-expand';
import { DataSource } from 'typeorm';

dotenvExpand.expand(dotenv.config());

export default new DataSource({
  type: 'mysql',
  host: process.env.DB_HOST,
  port: +process.env.DB_PORT,
  username: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  entities: ['dist/**/*.entity.js'],
  migrations: ['dist/database/migrations/*.js'],
  extra: {
    charset: 'utf8mb4_unicode_ci',
  },
 });

To generate a migration:

yarn run typeorm migration:generate -d dist/database/data-source -p src/database/migrations/[aNameForYourMigration]

Don't forget to change [aNameForYourMigration] by what you want

To run your migrations:

yarn run typeorm migration:run -d dist/database/data-source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM