【问题标题】:Why does the useFactory option make me an error in the nestjs configuration?为什么 useFactory 选项会让我在 nestjs 配置中出错?
【发布时间】:2020-01-25 04:46:09
【问题描述】:

Type '(configService: ConfigService) => Promise' 不可分配给类型 '(...args: any[]) => ({ retryAttempts?: number; retryDelay?: number; keepConnectionAlive?: boolean; } & Partial) | ({ retryAttempts?: number; retryDelay?: number; keepConnectionAlive?: boolean; } & Partial<...>) | ... 11 更多... |承诺<...>'。键入'承诺' 不可分配给类型 '({ retryAttempts?: number; retryDelay?: number; keepConnectionAlive?: boolean; } & Partial) | ({ retryAttempts?: number; retryDelay?: number; keepConnectionAlive?: boolean; } & Partial<...>) | ... 11 更多... |承诺<...>'。键入'承诺' 不可分配给类型 'Promise'。类型'{类型:字符串;端口:字符串;用户名:字符串;密码:字符串;数据库:字符串;主机:字符串;实体:字符串[];同步:布尔值; }' 不可分配给类型 'TypeOrmModuleOptions'。类型'{类型:字符串;端口:字符串;用户名:字符串;密码:字符串;数据库:字符串;主机:字符串;实体:字符串[];同步:布尔值; }' 不可分配给类型 '{ retryAttempts?: number;重试延迟?:数字; keepConnectionAlive?: 布尔值; } & 部分的'。 类型'{类型:字符串;端口:字符串;用户名:字符串;密码:字符串;数据库:字符串;主机:字符串;实体:字符串[];同步:布尔值; }' 不可分配给类型 'Partial'。 属性“类型”的类型不兼容。 类型 '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.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 选项是产生错误的选项,但我不明白为什么 我感谢任何人的帮助

【问题讨论】:

    标签: node.js nestjs typeorm


    【解决方案1】:

    所以问题是当我尝试从 .env 文件中获取端口时,必须将类型转换为数字。示例:

    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,
    }),
    

    解决问题

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多