与Nestjs和Typeorm共享环境配置,但迁移不会生成

发布于 2025-02-13 23:59:59 字数 3001 浏览 1 评论 0原文

我已经能够将ConfigService与我的TypeOmm(v0.3.7)配置一起使用,因此我的环境(.ENV)文件被编写,并在NRWL NX(V14)中使用我的Nestjs(v8.4.7)应用程序。 4.2)单声道存储库。我通过Nestjs的数据库访问工作正常。

我已经创建了一个数据库配置类(数据库。

数据库

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

export default class DatabaseConfiguration {
    static GetORMConfiguration(ConfigService_: ConfigService): TypeOrmModuleOptions {
        return {
            type: 'mysql',
            host: ConfigService_.get('DB_SERVER_HOST') || 'localhost',
            port: parseInt(ConfigService_.get('DB_SERVER_PORT'), 10) || 3306,
            username: ConfigService_.get('DB_USER') || 'username',
            password: ConfigService_.get('DB_PASSWORD') || 'password',
            database: ConfigService_.get('DB_DATABASE') || 'dbname',
            autoLoadEntities: true,
            synchronize: false,
            migrationsRun: false,
            logging: ['error', 'schema', 'warn'],
            maxQueryExecutionTime: 1000,
            logger: 'file',
        };
    }
}

export const DatabaseConfigurationAsync: TypeOrmModuleAsyncOptions = {
    imports: [ConfigModule],
    useFactory: async (ConfigService_: ConfigService): Promise<TypeOrmModuleOptions> => DatabaseConfiguration.GetORMConfiguration(ConfigService_),
    inject: [ConfigService]
};

。 -not-with-with-configservice“>这个问题和答案:

app.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';

import { DatabaseConfigurationAsync } from './database.configuration';

import { AdminCodesModule } from './admin-codes/admin-codes.module';

import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
    imports: [
        ConfigModule.forRoot({ isGlobal: true }),
        TypeOrmModule.forRootAsync(DatabaseConfigurationAsync),

        AdminCodesModule,
    ],
    controllers: [AppController],
    providers: [AppService],
})
export class AppModule {}

然后,我对管理代码有一个简单的定义,可以简单地拥有一个数据库。与控制器,服务等的API一起工作,我确实会收到所有数据。但是,当我尝试生成迁移时,无论我如何继续尝试更改代码,我都会发现我无法解决的错误。

尝试运行命令(通过NPM和package.json或bash shell):

npx typeorm-ts-node-commonjs migration:generate -d ./app/database.configuration.ts ./migrations/admincodes

npx typeorm-ts-node-commonjs migration:generate -d ./app/database.configuration.ts admincodes

给出一个错误:

Error during migration generation:
Error: Unable to open file: "repo\apps\api\src\app\database.configuration.ts". Cannot use import statement outside a module

我尝试更改多种方式,包括甚至移动类型:module在我的package.json中,并使用typeorm-ts-node-esm运行生成,但是每个版本都会在导入错误的某些部分或type中失败,或使用类型:模块导出行失败。

我不能在package.json中使用类型:模块,因为这会破坏Nestjs应用程序中的其他功能。

I have been able to get the ConfigService to work with my TypeORM (v0.3.7) configuration, so my environment (.env) file is being written, and works with my NestJS (v8.4.7) application in a Nrwl NX (v14.4.2) mono repository. My database access via NestJS is working fine.

I have created a database configuration class (database.configuration.ts) which gets my information for the database connection from the .env file using the NestJS Configuration module.

database.configuration.ts

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

export default class DatabaseConfiguration {
    static GetORMConfiguration(ConfigService_: ConfigService): TypeOrmModuleOptions {
        return {
            type: 'mysql',
            host: ConfigService_.get('DB_SERVER_HOST') || 'localhost',
            port: parseInt(ConfigService_.get('DB_SERVER_PORT'), 10) || 3306,
            username: ConfigService_.get('DB_USER') || 'username',
            password: ConfigService_.get('DB_PASSWORD') || 'password',
            database: ConfigService_.get('DB_DATABASE') || 'dbname',
            autoLoadEntities: true,
            synchronize: false,
            migrationsRun: false,
            logging: ['error', 'schema', 'warn'],
            maxQueryExecutionTime: 1000,
            logger: 'file',
        };
    }
}

export const DatabaseConfigurationAsync: TypeOrmModuleAsyncOptions = {
    imports: [ConfigModule],
    useFactory: async (ConfigService_: ConfigService): Promise<TypeOrmModuleOptions> => DatabaseConfiguration.GetORMConfiguration(ConfigService_),
    inject: [ConfigService]
};

Then I have updated by app.module.ts to import and use this information, based on this question and answers:

app.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';

import { DatabaseConfigurationAsync } from './database.configuration';

import { AdminCodesModule } from './admin-codes/admin-codes.module';

import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
    imports: [
        ConfigModule.forRoot({ isGlobal: true }),
        TypeOrmModule.forRootAsync(DatabaseConfigurationAsync),

        AdminCodesModule,
    ],
    controllers: [AppController],
    providers: [AppService],
})
export class AppModule {}

I have a simple definition then for the Administration Codes, to simply have a database. Working with the API from the controller, service, etc., I do receive all my data back. However, when I try to generate the migrations, I get an error that I cannot resolve no matter how I keep trying to change the code.

Trying to run the commands (via npm and package.json or the bash shell):

npx typeorm-ts-node-commonjs migration:generate -d ./app/database.configuration.ts ./migrations/admincodes

or

npx typeorm-ts-node-commonjs migration:generate -d ./app/database.configuration.ts admincodes

gives an error:

Error during migration generation:
Error: Unable to open file: "repo\apps\api\src\app\database.configuration.ts". Cannot use import statement outside a module

I have tried changing this many ways, including even moving to type: module in my package.json, and using typeorm-ts-node-esm to run the generation, but each version fails with some part of the import error, or with type: module the export line fails.

I cannot use the type: module in my package.json as that breaks other functionality in the NestJS application.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我做我的改变 2025-02-20 23:59:59

这是我配置它的简单方法

npm i @nestjs/config

    @Module({
  imports: [
    ConfigModule.forRoot(),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      name: process.env.DATABASE_NAME,
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => {
        return {
          type: 'mysql',
          host: configService.get(`DATABASE_HOST`),
          port: configService.get(`DATABASE_PORT`),
          username: configService.get('DB_USER'),
          database: configService.get('DATABASE_NAME'),
          password: configService.get('DB_PASSWORD'),
          entities: [__dirname + '/../entities/*.entity{.ts,.js}'],
          synchronize: false,
          logging: true,
        };
      },
    }),
  ],

this is the simple way i configure it

npm i @nestjs/config

    @Module({
  imports: [
    ConfigModule.forRoot(),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      name: process.env.DATABASE_NAME,
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => {
        return {
          type: 'mysql',
          host: configService.get(`DATABASE_HOST`),
          port: configService.get(`DATABASE_PORT`),
          username: configService.get('DB_USER'),
          database: configService.get('DATABASE_NAME'),
          password: configService.get('DB_PASSWORD'),
          entities: [__dirname + '/../entities/*.entity{.ts,.js}'],
          synchronize: false,
          logging: true,
        };
      },
    }),
  ],
故事灯 2025-02-20 23:59:59

错误指定路径不正确,并且无法打开文件。
检查您的DIST文件夹,并在构建应用程序时检查文件的生成位置。

我认为您必须在路径中添加/src
./src/app/database.configuration.ts ./migrations/admincodes。

The error specify that the path is incorrect, and can't open the file.
check your dist folder, and check where the file is generate when you build your app.

I think you have to add /src in your path:
./src/app/database.configuration.ts ./migrations/admincodes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文