最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

为什么useFactory选项使我在nestjs配置中出错?

运维笔记admin10浏览0评论

为什么useFactory选项使我在nestjs配置中出错?

为什么useFactory选项使我在nestjs配置中出错?

Type'(configService:ConfigService)=>承诺'不可分配为类型((... args:any [])=>({retryAttempts ?: number; retryDelay ?: number; keepConnectionAlive ?: boolean;}&Partial)| ({{retryAttempts ?: number; retryDelay ?: number; keepConnectionAlive ?: boolean;}&Partial <...>)| ... 11更多... |无极<...>”。输入'Promise '不可分配给类型'({{retryAttempts ?: number; retryDelay ?: number; keepConnectionAlive ?: boolean;}&Partial)| ({{retryAttempts ?: number; retryDelay ?: number; keepConnectionAlive ?: boolean;}&Partial <...>)| ... 11更多... |无极<...>”。输入'Promise '不能分配给'Promise'类型。类型'{type:string; port:字符串;用户名:字符串;密码:字符串;数据库:字符串;主机:字符串;实体:string [];同步:布尔值; }”不能分配给“ TypeOrmModuleOptions”类型。类型'{type:string; port:字符串;用户名:字符串;密码:字符串;数据库:字符串;主机:字符串;实体:string [];同步:布尔值; }'不能分配给类型'{retryAttempts ?: number; retryDelay ?:数字; keepConnectionAlive ?:布尔值; }&Partial'。类型'{type:string; port:字符串;用户名:字符串;密码:字符串;数据库:字符串;主机:字符串;实体:string [];同步:布尔值; }”不可分配给“部分”类型。属性“类型”的类型不兼容。类型'string'不可分配给类型'“ aurora-data-api”'。

这是nestjs给我的消息,我按照文档中的说明进行操作,但不适用于我。

这是我的app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CategoryModule } from './category/category.module';
import { ProductModule } from './product/product.module';
import { UnitModule } from './unit/unit.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from './config/config.module';
import { ConfigService } from './config/config.service';
import { RolModule } from './rol/rol.module';
import { UserModule } from './user/user.module';
import { AuthModule } from './auth/auth.module';

@Module({
  imports: [TypeOrmModule.forRootAsync({
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory: async (configService: ConfigService) => ({
      type: 'mysql',
      port: configService.port,
      username: configService.username,
      password: configService.password,
      database: configService.database,
      host: configService.host,
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true,
    }),
  }), CategoryModule, UnitModule, ProductModule, RolModule, UserModule, AuthModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

这是我的config / config.service.ts

import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as Joi from '@hapi/joi';

export interface EnvConfig {
    [key: string]: string;
}

export class ConfigService {
    private readonly envConfig: EnvConfig;

    constructor(filePath: string) {
        const config = dotenv.parse(fs.readFileSync(filePath));
        this.envConfig = this.validateInput(config);
    }

    private validateInput(envConfig: EnvConfig): EnvConfig {
        const envVarsSchema: Joi.ObjectSchema = Joi.object({
            NODE_ENV: Joi.string()
            .valid('development', 'production', 'test', 'provision')
            .default('development'),
            PORT: Joi.number().default(3000),
            HOST: Joi.strict(),
            USERNAME: Joi.string(),
            PASSWORD: Joi.string(),
            DATABASE: Joi.string(),
        });

        const { error, value: validatedEnvConfig } = envVarsSchema.validate(
            envConfig,
        );
        if (error) {
            throw new Error(`Config validation error: ${error.message}`);
        }
        return validatedEnvConfig;
    }

    get port(): string {
        return String(this.envConfig.PORT);
    }
    get host(): string {
        return String(this.envConfig.HOST);
    }
    get username(): string {
        return String(this.envConfig.USERNAME);
    }
    get password(): string {
        return String(this.envConfig.PASSWORD);
    }
    get database(): string {
        return String(this.envConfig.DATABASE);
    }
}

这是我的config / config.module.ts

import { Module } from '@nestjs/common';
import { ConfigService } from './config.service';

@Module({
  providers: [{
    provide: ConfigService,
    useValue: new ConfigService(`${process.env.NODE_ENV || 'development'}.env`),
  }],
  exports: [ConfigService],
})
export class ConfigModule {}

useFacetory选项是产生错误的选项,但我不明白为什么我感谢任何人的帮助

回答如下:

所以问题是,当我尝试从.env文件获取PORT时,有必要将类型转换为Number。例如:

useFactory: async (configService: ConfigService) => ({
  type: 'mysql',
  port: Number(configService.port),
  username: configService.username,
  password: configService.password,
  database: configService.database,
  host: configService.host,
  entities: [__dirname + '/**/*.entity{.ts,.js}'],
  synchronize: true,
}),

解决了问题

发布评论

评论列表(0)

  1. 暂无评论