首页 > 解决方案 > 生成迁移时如何从秘密存储中动态添加 TypeOrm 配置?

问题描述

我正在尝试与 TypeOrm 建立一个 postgres 连接,该连接从秘密源(异步)动态提取配置并生成新的迁移。

我尝试使用 async await 异步设置在 typeorm-cli 运行时 postgres.config.ts 文件将使用的环境变量和局部变量,但我不断收到错误。

// src/config/defaults/postgres.config.ts

const postgresConfig = (async () => {
  try {
    const db: PostgresConfig = await secretsSource.getSecret();

    return {
        type: 'postgres',
        host: db.host,
        port: db.port,
        username: db.username,
        password: db.password,
        database: db.database,
        entities: [path.join(__dirname, '../**/*.entity{.ts,.js}')],
        migrationsRun: true,
        logging: true,
        logger: 'file',
        migrations: [path.join(__dirname, '../migrations/**/*{.ts,.js}')],
        cli: {
          migrationsDir: 'src/migrations',
        },
    } as ConnectionOptions;
  } catch (error) {
      // ... handle error
  }
})();

export default postgresConfig;

// package.json

{
    scripts: {
        "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/config/defaults/postgres.config.ts",
        "typeorm:migrate": "npm run typeorm migration:generate -- -n",
        "typeorm:run": "npm run typeorm migration:run"
    }
};

我希望在运行“npm run typeorm:migrate initial”时,脚本会指向配置文件异步运行文件,等待代码提供必要的数据库配置,并生成迁移,但似乎脚本没有'不按预期运行任何代码,我不断收到以下错误:

迁移生成期间出错:{ MissingDriverError:错误的驱动程序:给出了“未定义”。支持的驱动程序是:.....}

我需要动态获取数据库配置,因为我有不同的环境需要不同的配置。

标签: node.jstypescripttypeorm

解决方案


推荐阅读