标签: nestjs-config

如何在 super() 中使用 configService?

我有一个关于设置环境变量的问题。

在官方文档中,它说在这种情况下使用ConfigModule,但我的情况是一个例外情况。

因为我想在构造函数的 super() 中使用它。

我的代码如下。

这种情况有什么解决办法吗?

如果您需要更多信息,请告诉我。

谢谢大家的支持!!

// jwt.strategy.ts

import { UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { JwtPayload } from './jwt-payload.interface';
import { UserRepository } from './user.repository';
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(
        @InjectRepository(UserRepository)
        private userRepository: UserRepository,
        private configService: ConfigService,
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: configService.get('JWT_TOKEN'),
        });
    }

    async validate(payload: JwtPayload) …
Run Code Online (Sandbox Code Playgroud)

nestjs nestjs-passport nestjs-config nestjs-jwt

10
推荐指数
2
解决办法
4763
查看次数

Nest.js 无法解析依赖关系

ConfigService我正在尝试在我的中使用,users.module.ts但我得到了

错误:Nest 无法解析 UsersService(UserRepository、HttpService、?)的依赖项。请确保索引 [2] 处的参数 ConfigService 在 UsersModule 上下文中可用。

潜在的解决方案:

  • 如果 ConfigService 是提供者,它是当前 UsersModule 的一部分吗?
  • 如果 ConfigService 是从单独的 @Module 导出的,那么该模块是否会在 UsersModule 中导入?

我已将 ConfigModule 导入到我的 UsersModule 中,但仍然无法正常工作:(

应用程序模块.ts

@Module({
  imports: [
    ConfigModule.forRoot({
      expandVariables: true,
    }),
    TypeOrmModule.forRoot(),
    UsersModule,
    AuthModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})

export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

用户.module.ts

import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [ConfigModule, HttpModule, TypeOrmModule.forFeature([User])],
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService],
})

export class UsersModule {}
Run Code Online (Sandbox Code Playgroud)

用户.service.ts

export class UsersService { …
Run Code Online (Sandbox Code Playgroud)

typescript nestjs nestjs-config

9
推荐指数
1
解决办法
3万
查看次数

eslint + jsconfig + nextjs 模块路径别名(绝对路径导入 - @)

我正在尝试按照nextjs 文档使用自定义别名导入文件。

我目前的做法是

import Header from '../../../components/Header';
Run Code Online (Sandbox Code Playgroud)

import Header from '@components/Header';
Run Code Online (Sandbox Code Playgroud)

我得到了预期的结果。但是 eslint 会抛出以下错误:

  • 无法解析模块路径(eslint - 导入/没有未解析)

我尝试在 eslintrc 文件中添加以下行来解决该错误

    settings: {
    'import/resolver': {
      node: {
        paths: ['src'],
      },
    },
  },
Run Code Online (Sandbox Code Playgroud)

但 eslint 仍然抛出同样的错误。

解决这个问题的正确方法是什么?

提前致谢...

注意:我不想删除 eslint 并且我需要 @components import 别名

import reactjs next.js eslintrc nestjs-config

8
推荐指数
2
解决办法
4713
查看次数

如何在Nestjs DatabaseModule中使用ConfigService

我使用Nestjs typeorm创建了一个 DatabaseModule

import { createConnection } from 'typeorm';
import { ConfigService } from '@nestjs/config';


export const databaseConnection = [
    {
        provide: 'DATABASE_CONNECTION',
        useFactory: async (configService: ConfigService) => await createConnection({
            type: configService.get('DBTYPE'),
            host: configService.get('DBHOST'),
            port: configService.get('DBPORT'),
            username: configService.get('DBUSERNAME'),
            password: configService.get('DBPASSWORD'),
            database: configService.get('DBNAME'),
            synchronize: true,
            entities: [
                __dirname + '/../**/*.entity.ts'
            ]
        })
    }
];
Run Code Online (Sandbox Code Playgroud)

启动其余服务时,出现以下错误

Cannot read property 'get' of undefined - {"stack":["TypeError: Cannot read property 'get' of undefined

    at InstanceWrapper.useFactory [as metatype] (../database/database.provider.js:9:33)
    at Injector.instantiateClass (../node_modules/@nestjs/core/injector/injector.js:293:55)
    at callback (../node_modules/@nestjs/core/injector/injector.js:77:41) …
Run Code Online (Sandbox Code Playgroud)

typeorm nestjs nestjs-config

7
推荐指数
1
解决办法
1万
查看次数

NestJS 配置部分注册与验证

在 NestJS 文档中有一个关于部分注册的部分。它说它允许在不同的目录中加载特定于功能的配置文件:

import databaseConfig from './config/database.config';

@Module({
  imports: [ConfigModule.forFeature(databaseConfig)],
})
export class DatabaseModule {}
Run Code Online (Sandbox Code Playgroud)

但是,似乎不可能提供特定于功能的验证模式,因为这Config是您可以为该方法提供的唯一参数forFeature。我是否正确地假设我需要在ConfigModule.forRoot方法中提供此数据库配置验证架构?这似乎违背了功能特定配置文件的目的,因为验证需要在更高的位置定义?

还有其他方法可以通过验证实现部分注册吗?

nestjs nestjs-config

7
推荐指数
1
解决办法
1042
查看次数

如何在实例化应用程序之前在 main.ts 中获取 Nestjs configService 实例

我的应用程序实例取决于配置:serviceName在这种情况下

const serviceName = 'authentication-service'
const servicePrefix = `api/${serviceName}`;
const swaggerPrefix = 'swagger';
...
const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter({
      requestIdLogLabel: serviceName,
      logger: true,
      ...
    }),
    {
      // logger: ['log']
      logger: process.env.DEV === '1' ? ['log', 'debug', 'error', 'verbose', 'warn'] : ['error', 'warn'],
    });
Run Code Online (Sandbox Code Playgroud)

NestJs 文档使用 app 实例来获取configService单例:

const configService = app.get(ConfigService);
const port = configService.get('PORT');
Run Code Online (Sandbox Code Playgroud)

在实例化我的应用程序之前有什么方法可以获取configService实例吗?

nestjs nestjs-config

7
推荐指数
1
解决办法
5180
查看次数

NestJS ConfigService 在应用启动时的异步 TypeORM 配置期间返回未定义的值

我正在尝试按照以下一些文档为我的 NestJS 应用程序设置配置:

配置: https: //docs.nestjs.com/techniques/configuration

TypeORM: https: //docs.nestjs.com/techniques/database#async-configuration

我已将 .env 文件添加到项目的根目录(与 相同级别package.json),其中包含以下值:

DB_URL=localhost
DB_USER=root
DB_PASSWORD=root
DB_NAME=test_db
Run Code Online (Sandbox Code Playgroud)

在我的 app.module.ts 中,我导入以下模块:

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

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

@Module({
  imports: [
    ConfigModule.forRoot(),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => {
        // The value logged below is undefined'
        console.log(`DB URL: ${configService.get('DB_URL')}`);
        return {
          type: 'mysql',
          host: …
Run Code Online (Sandbox Code Playgroud)

nestjs nestjs-config

7
推荐指数
0
解决办法
2562
查看次数

Nestjs微服务中的动态kafka主题名称

在 Nestjs 中,我使用 kafka 作为消息代理并设置主题名称,如下所示:

@MessagePattern('topic-name')
async getNewRequest(@Payload() message: any): Promise<void> {
  // my code goes here
}
Run Code Online (Sandbox Code Playgroud)

有没有办法从配置服务模块读取kafka主题名称?

typescript microservices nestjs nestjs-config

7
推荐指数
1
解决办法
2027
查看次数

@graphql-eslint/eslint-plugin“parserOptions.schema”错误

我们正在使用 NestJS-typescript 开发微服务。

它们每个都公开一个 GraphQL 模式。为了公开单个图,我们也在 NestJS 中使用联合服务。

我试图与“@graphql-eslint/eslint-plugin”集成。

该插件的作用分为2个:

  1. 没有任何要求的角色 - 效果很好。
  2. 需要架构/操作文件的角色 - 失败。

第 2# 节角色需要有关模式文件的附加信息。正如我之前所说,有许多架构和操作文件位于 monorepo 中。

正如文档中提到的,为了允许这些角色,应该定义“parserOptions.schema”。无论我做了什么,我都无法设置该字段,并且收到以下错误:

错误:规则“unique-argument-names”需要设置“parserOptions.schema”并加载架构。有关更多信息,请参阅https://github.com/dotansimha/graphql-eslint#extended-linting-rules-with-graphql-schema

在我的 POV 中,我只希望 linter 访问.graphql整个项目中的所有文件,但我不知道为什么这不起作用以及为什么需要这个字段,因为我已经将 linter 定义为仅 lint*.graphql文件。

typescript eslint graphql graphql-js nestjs-config

7
推荐指数
1
解决办法
1651
查看次数

NestJS:如何自定义日志消息以包含请求 ID 和发生日志消息的文件名称

我是 NestJS 的新手,想要自定义日志消息以包含 x-request-id/x-correlation-id 以及日志消息所源自的文件的名称,但不确定 NestJS 中是否有任何内容可以做到这一点。

我的应用程序将 NestJS 与 Fastify 适配器结合使用,并在 bootstrap() 函数中进行以下配置

  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
    {
        logger: WinstonModule.createLogger(winston.createLogger({
          exitOnError: false,
          level: 'debug',
          handleExceptions: true,
          format: winston.format.combine(
            winston.format.timestamp(),
            winston.format.ms(),
            winston.format.colorize(),
            winston.format.align(),
            winston.format.splat(),
            winston.format.printf((info) => {
                return `${info.timestamp} [ ${info.level} ] : ${info.message}`;
            }),
          ),
          transports: [
            new (winston.transports.Console)()
          ]
        }),
      )
    }
  );
Run Code Online (Sandbox Code Playgroud)

这似乎按预期使用温斯顿格式化日志。

2022-03-09T11:21:22.131Z [ info ] : Starting Nest application...

但是,我还想在消息中包含请求/相关 ID 以及发生日志消息的文件名,例如

2022-03-09T11:21:22.131Z 2cfd4eee-ca2b-4869-b66b-2b7da291f567 [ info ] [ Main.ts ]: Starting …

logging winston nestjs nestjs-config nest-winston

7
推荐指数
2
解决办法
2万
查看次数