[英]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.我想知道是否有人知道如何在 NestJS 环境中使用来自 TypeORM 的异步数据源生成和运行迁移。
What I mean with async DataSource
is that the values of the database connection are fetched on the fly (from a secret manager provider).我对
async DataSource
的意思是,数据库连接的值是动态获取的(来自秘密管理器提供者)。
There is a PR with this information here but, what is the best practice to merge this "concept" into NestJS?.这里有一个包含此信息的 PR,但是,将此“概念”合并到 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
(并在开始嵌套时按预期工作):
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.该问题的 Github 链接已在此处更新,特别是 DanielMaranhao。 Personally, I still use 2 datasources (one for migrations and one for Nest configuration)
就个人而言,我仍然使用 2 个数据源(一个用于迁移,一个用于 Nest 配置)
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”的文件
// 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不要忘记根据需要更改[aNameForYourMigration]
To run your migrations:运行迁移:
yarn run typeorm migration:run -d dist/database/data-source
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.