TypeORM:在没有专用 ormconfig 文件的情况下生成迁移

TypeORM: Generate migrations without dedicated ormconfig file

TypeORM(json、env、yml...)提供的几种连接到数据库的方法中,我选择以编程方式设置我的连接选项我的项目代码使用常规 TypeScript 文件如下:

// src/database/createConnection.ts

import { createConnection } from 'typeorm';

    const connectionOptions = {
        type: 'postgres',
        host: POSTGRES_HOST_PROD,
        port: Number(POSTGRES_PORT),
        username: POSTGRES_USER,
        password: POSTGRES_PASSWORD,
        database: POSTGRES_DB,
        entities: ['build/entities/**/typeDef.js'],
        migrations: ['build/database/migrations/*.js'],
        cli: {
            migrationsDir: 'src/database/migrations/'
        }
    };

await createConnection(connectionOptions);

使用常规 .env 文件提供的值。

我的问题是,尝试通过 npx typeorm migration:generate -n initial 创建迁移文件时出现错误,因为该命令需要存在特定的 orm 配置文件(ormconfig.env、ormconfig.json、等)。

因为我已经设置了连接选项,这不仅是多余的,而且还会被处理,而不是我已经在 .ts 文件中设置的配置,我看到的唯一解决方案是重命名我的(非 typeorm 特定的).env 文件中的变量以匹配 specific TypeORM variable names,我不想这样做。


TL:DR 有没有一种方法可以在不创建专用 orm 配置文件的情况下生成 TypeORM 迁移?


哦,原来 TypeORM 已经为此内置了一个选项,不需要额外的 ormconfig 文件,只需将 属性 migrationsRun: true 添加到连接选项(确保synchronize 设置为 false)。

例如:

从'typeorm'导入{createConnection};

const connectionOptions = {
    type: 'postgres',
    host: POSTGRES_HOST_PROD,
    port: Number(POSTGRES_PORT),
    username: POSTGRES_USER,
    password: POSTGRES_PASSWORD,
    database: POSTGRES_DB,
    migrationsRun: true,
    entities: ['build/entities/**/typeDef.js'],
    migrations: ['build/database/migrations/*.js'],
    cli: {
        migrationsDir: 'src/database/migrations/'
    }
};

await createConnection(connectionOptions);