使用 `useFactory` 运行迁移

问题描述 投票:0回答:3

我的应用程序位于

nestjs
中,其中
app.module.ts
包含以下配置:

import { ConfigModule, ConfigService } from '@nestjs/config';
import {
  TypeOrmModuleAsyncOptions,
  TypeOrmModuleOptions,
} from '@nestjs/typeorm';
import { DataSource } from 'typeorm';  

export const typeOrmAsyncConfig: TypeOrmModuleAsyncOptions = {
  imports: [ConfigModule],
  inject: [ConfigService],
  name: 'nameA',
  useFactory: (configService: ConfigService) => ({
    type: 'postgres',
    host: configService.get('DB_HOST'),
    port: parseInt(configService.get('DB_PORT') || '5432'),
    username: configService.get('DB_USER'),
    password: configService.get('DB_PASSWORD'),
    database: configService.get('DB_NAME'),
    entities: [__dirname + './../**/*.entity{.ts,.js}'],
    migrations: [__dirname + '/../database/migrations/*{.ts,.js}'],
    synchronize: false,
    cli: {
      entitiesDir: __dirname + './../**/*.entity{.ts,.js}',
    },
    ssl: configService.get('DB_SSL') === 'true',
  }),
};

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    TypeOrmModule.forRootAsync(typeOrmAsyncConfig),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

我已经全局安装了

typeorm
,并在上面的指定路径中生成了迁移文件,但是,我收到了
dataSource
未找到错误。

typeorm migration:run
输出:

Runs all pending migrations.

Options:
  -h, --help         Show help                                         [boolean]
  -d, --dataSource   Path to the file where your DataSource instance is defined.
                                                                      [required]
  -t, --transaction  Indicates if transaction should be used or not for
                     migration run. Enabled by default.     [default: "default"]
  -v, --version      Show version number                               [boolean]

Missing required argument: dataSource

当我在

useFactory
内部使用
app.module.ts
时,如何导出数据源并解决这个问题?

typeorm nest
3个回答
6
投票

由于 typeorm 0.3.x cli 需要数据源,并且不再支持 ormconfig.json。 cli 命令也发生了变化。 您可以为nestjs和typeorm-cli定义单独的配置。

src/config/database-config.ts

    import 'dotenv/config';
    import { DataSourceOptions } from 'typeorm';
    
    const databaseConfig: DataSourceOptions = {
      name: 'default',
      type: 'better-sqlite3',
      database: process.env.DB_NAME,
      entities: [__dirname + '/../entities/*.entity.ts'],
      migrations: [__dirname + '/../migrations/*{.ts,.js}'],
      synchronize: false,
      logging: true,
      migrationsRun: true
    };
    
    export default databaseConfig;

然后是 typeorm cli

src/config/data-source.ts

    import { DataSource } from 'typeorm';
    import databaseConfig from './database-config';
    
    export const AppDataSource = new DataSource(databaseConfig);

对于 Nestjs 应用程序模块

src/config/typeorm-config.ts
like so: TypeOrmModule.forRootAsync(typeOrmAsyncConfig)

    import { ConfigModule, ConfigService } from '@nestjs/config';
    import {
      TypeOrmModuleAsyncOptions,
      TypeOrmModuleOptions,
    } from '@nestjs/typeorm';
    import databaseConfig from './database-config';
    
    export const typeOrmConfig: TypeOrmModuleOptions = databaseConfig;
    
    export const typeOrmAsyncConfig: TypeOrmModuleAsyncOptions = {
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (): Promise<TypeOrmModuleOptions> => {
        return databaseConfig;
      },
    };

package.json 脚本(如果需要,更改yarn run)

    {
    "typeorm:cli": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -d src/config/data-source.ts",
    "migration:generate": "yarn run typeorm:cli migration:generate",
    "migration:create": "yarn run typeorm:cli migration:create",
    "migration:run": "yarn run typeorm:cli migration:run",
    "migration:revert": "yarn run typeorm:cli migration:revert"
    }

例如如果您需要生成新的迁移所需的完整路径 在终端

yarn run migration:generate src/migrations/newMigrationName

0
投票

对于向上迁移似乎有一种方便的方法,但是,由于答案是部分的,我不会将其标记为完成:

   {
     imports: [ConfigModule],
     inject: [ConfigService],
     useFactory: (configService: ConfigService) => ({
       type: 'postgres',
       host: configService.get('DB_HOST'),
       port: parseInt(configService.get('DB_PORT') || '4432'),
       username: configService.get('DB_USER'),
       password: configService.get('DB_PASSWORD'),
       database: configService.get('DB_NAME'),
       entities: [MyEntity],
       migrations: ['./**/*.migration.js'],
       synchronize: false,
       ssl: configService.get('DB_SSL') === 'true',
     }),
     dataSourceFactory: async (options: DataSourceOptions) => {
       const dataSource = await new DataSource(options).initialize();
       await dataSource.runMigrations();
   
       return dataSource;
     },
   }  

如果添加了新的迁移,则应在服务器重新启动后应用它们。


0
投票

在这种情况下,我们会回到节点;-) 使用 dotenv 更好。 试试这个制作一个数据库模块 添加此提供程序database.provider.ts

import { registerAs } from "@nestjs/config";
import { config as dotenvConfig } from 'dotenv';
import { DataSource, DataSourceOptions } from "typeorm";

dotenvConfig({ path: '.env.dev' });

const config = {
    type: 'postgres',
    host: `${process.env.POSTGRES_HOST}`,
    port: `${process.env.POSTGRES_PORT}`,
    username: `${process.env.POSTGRES_USER}`,
    password: `${process.env.POSTGRES_PASSWORD}`,
    database: `${process.env.POSTGRES_DB}`,
    entities: ["dist/**/*.entity{.ts,.js}"],
    migrations: ["dist/migrations/*{.ts,.js}"],
    autoLoadEntities: true,
    synchronize: false,
}

export default registerAs('typeorm', () => config)
export const connectionSource = new DataSource(config as DataSourceOptions);

对于您的数据库模块

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import typeorm from './database.provider';


@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, load: [typeorm]
    }), // Make ConfigModule global
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => (configService.get('typeorm'))
    }),
  ],
})
export class DatabaseModule { }

将此添加到包 json

"typeorm": "ts-node ./node_modules/typeorm/cli",
"migration:run": "npm run typeorm migration:run -- -d ./src/database/database.provider.ts",
"migration:generate": "npm run typeorm -- -d ./src/config/database.provider.ts migration:generate ./src/migrations/$npm_config_name",
"migration:create": "npm run typeorm -- migration:create ./src/migrations/$npm_config_name",
"migration:revert": "npm run typeorm -- -d ./src/database/database.provider.ts migration:revert"
© www.soinside.com 2019 - 2024. All rights reserved.