标签: nestjs

如何对扩展抽象类读取环境变量的类进行单元测试

我想要进行单元测试,并为我想要测试的 Nest API 提供一些配置服务。启动应用程序时,我使用 joi 包验证环境变量。

我有多个数据库、服务器的配置服务……所以我首先创建了一个基本服务。它能够读取环境变量,将原始字符串解析为所需的数据类型并验证该值。

import { ConfigService } from '@nestjs/config';
import { AnySchema, ValidationResult, ValidationError } from '@hapi/joi';

export abstract class BaseConfigurationService {
    constructor(protected readonly configService: ConfigService) {}

    protected constructValue(key: string, validator: AnySchema): string {
        const rawValue: string = this.configService.get(key);

        this.validateValue(rawValue, validator, key);

        return rawValue;
    }

    protected constructAndParseValue<TResult>(key: string, validator: AnySchema, parser: (value: string) => TResult): TResult {
        const rawValue: string = this.configService.get(key);
        const parsedValue: TResult = parser(rawValue);

        this.validateValue(parsedValue, validator, key);

        return parsedValue;
    }

    private validateValue<TValue>(value: TValue, …
Run Code Online (Sandbox Code Playgroud)

unit-testing node.js jestjs nestjs

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

Nestjs升级到7后无法启动

我今天将 Nest 应用从 6 升级到 7。解决所有打字稿错误后,我在启动时遇到奇怪的行为。

[Nest] 15484   - 05/01/2020, 3:33:29 PM   [NestFactory] Starting Nest application...
[Nest] 15484   - 05/01/2020, 3:33:29 PM   [InstanceLoader] GraphqlClientModule dependencies initialized +138ms
[Nest] 15484   - 05/01/2020, 3:33:29 PM   [InstanceLoader] SentryModule dependencies initialized +1ms
[Nest] 15484   - 05/01/2020, 3:33:29 PM   [InstanceLoader] TypeOrmModule dependencies initialized +0ms
[Nest] 15484   - 05/01/2020, 3:33:29 PM   [InstanceLoader] HttpModule dependencies initialized +2ms
[Nest] 15484   - 05/01/2020, 3:33:29 PM   [InstanceLoader] JwtModule dependencies initialized +0ms
[Nest] 15484   - 05/01/2020, 3:33:29 PM   [InstanceLoader] ConfigHostModule dependencies …
Run Code Online (Sandbox Code Playgroud)

nestjs

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

TypeORM自定义存储库,从指定列中选择不同的值

在我使用 Nestjs + typeorm + postgresql 的后端中,我有一个 CustomRepository 并且想要替换一些普通的 sql 查询。

这就是我所拥有的

const sqlQuery = `SELECT DISTINCT "myColumn" FROM "myTable"`
const sqlRes = await this.query(sqlQuery);
Run Code Online (Sandbox Code Playgroud)

我正在尝试得到这样的东西

this.find({select:["myColumn"]}); // note the missing DISTINCT
Run Code Online (Sandbox Code Playgroud)

但这给了我完整的专栏,但我只想要不同的值。

我发现了很多奇怪的createQueryBuilder().select(DISTINCT "myColumn" FROM "...... etc...解决方案,与我的工作解决方案相比,它们并没有给我带来任何好处。

javascript postgresql typeorm nestjs

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

如何使用 Fastify 在 Nestjs 项目中配置 Helmet?

我正在使用Nestjs (7.x) 和Fastify(带有@nestjs/platform-fastify)。我正在尝试在我的项目 ( ) 中安装Helmetfastify-helmet,但我无法弄清楚如何将其与 Nestjs 集成/配置。将其带上飞机的正确方法是什么?

这是我的 Nestjs 引导程序:

import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { MainModule } from './main.module';
import * as helmet from 'fastify-helmet';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(MainModule);
  await app.listen(3000, 0.0.0.0);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)

helmet.js nestjs fastify nestjs-fastify

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

Nest 无法解析 MailerService 的依赖关系(?)

我正在尝试配置这个模块

完整的错误消息如下:

Nest can't resolve dependencies of the MailerService (?). Please make sure that the argument MAILER_OPTIONS at index [0] is available in the AppModule context.

我总是莫名其妙地收到此错误,什么 MAILER_OPTIONS?这些选项在哪里?文档中没有提及这方面的内容。完全不知道发生了什么。

这是我的应用程序模块:

@Module({
  imports: [
    MailerModule.forRoot({
      defaults: {
        from: '"No Reply" <noreply@example.com>',
      },
      template: {
        dir: path.join(process.env.PWD, 'templates/pages'),
        adapter: new HandlebarsAdapter(),
        options: {
          strict: true,
        },
      },
      options: {
        partials: {
          dir: path.join(process.env.PWD, 'templates/partials'),
          options: {
            strict: true,
          },
        },
      },
    }),
  ],
  controllers: [AppController],
  providers: [
    AppService,
    MailerService,
  ],
}) …
Run Code Online (Sandbox Code Playgroud)

javascript dependency-injection node.js typescript nestjs

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

如何从嵌套中的Request获取用户?

我无法从装饰器巢中的请求中获取用户,请帮助我。中间件工作良好,它通过令牌查找用户并将用户保存在请求我的中间件中:

import { Injectable, NestMiddleware, HttpStatus } from '@nestjs/common';
import { HttpException } from '@nestjs/common/exceptions/http.exception';
import { Request, Response } from 'express';
import { AuthenticationService } from '../modules/authentication-v1/authentication.service';

@Injectable()
export class AuthenticationMiddleware implements NestMiddleware {
    constructor(
        private readonly authenticationService : AuthenticationService
    ) {
    }
    async use(req: Request, res: Response, next: Function) {
        let token = req.headers;

        if(!token) {
            throw new HttpException('token is required', 401);
        }

        if (!token.match(/Bearer\s(\S+)/)) {
            throw new HttpException('Unsupported token', 401);
        }
        const [ tokenType, tokenValue ] = …
Run Code Online (Sandbox Code Playgroud)

javascript typescript nestjs

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

Nest.js 注入模型?

我有教程|中的以下代码:

constructor(@InjectModel('User') private readonly userModel: Model<User>) {}
Run Code Online (Sandbox Code Playgroud)

哪里User

export interface User extends Document {
  readonly name: string;
  readonly age: number;
  readonly phone: string;
}
Run Code Online (Sandbox Code Playgroud)

您能解释一下我们是如何@InjectModel运作的,是什么'User'以及为什么我们通过了Model<User>,这意味着什么?

我还可以使用什么注射@InjectModel

nestjs

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

Nest 构建在管道中失败:找不到本地构建时可以找到的模块

在我的 NestJS 项目中,本地构建和运行是可行的,但是当在我的 Azure 管道中构建相同的代码时,它最近开始失败,因为在命令中找不到某些模块npm run build。当我在本地运行该命令时,没有任何问题并且可以正确构建。

有许多模块确实可以正确找到(或没有给出错误),那么为什么这些模块不能呢?您可以在 Imgur 上的此图像中找到我的文件布局的图像,并且相关文件可见。所有类都被声明为,export class ... {}并且大多数类也被导入到 AppModule 中,它们不会给出错误。

管道布置(相关部分):

trigger:
  - master
  - dev

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: NodeTool@0
  displayName: 'Install Node 12'
  inputs:
    versionSpec: 12.0.0

- script: |
    npm install -g typescript
    npm install
    npm test
  displayName: 'run tests'

- script: |
    npm run build
  displayName: 'build dist folder'
Run Code Online (Sandbox Code Playgroud)

管道日志:(相关部分)

Generating script.
Script contents:
npm run build
========================== Starting Command Output ===========================

> fleetbot-nestjs@0.0.1 …
Run Code Online (Sandbox Code Playgroud)

node.js azure-pipelines nestjs azure-pipelines-yaml

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

如何在NestJs Bull中注册多个队列?

我正在尝试在 NestJs 中创建多个队列,文档说:

通过将多个逗号分隔的配置对象传递给 registerQueue() 方法来创建多个队列。

但这对我不起作用,因为当我尝试这样做时,VScode 建议我应该在逗号后面提及 Bull 选项。以下是我对单个队列的配置,如何注册多个队列?

@Module({
    imports: [
        ConfigModule,
        BullModule.registerQueueAsync({
            name: 'Queue1',
            imports: [ConfigModule],
            useFactory: async (configService: ConfigService) => ({
                redis: {
                    host: configService.get('QUEUE_HOST'),
                    port: +configService.get('QUEUE_PORT'),
                },
            }),
            inject: [ConfigService],
        }),
        HttpModule,
    ],
    controllers: [ScheduleController],
    providers: [MainConsumer], //Service is included here
})

export class AppModule {}

Run Code Online (Sandbox Code Playgroud)

cron config typescript nestjs

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

NestJS/TypeORM 项目的物化视图

我正在尝试使用 TypeORM 从我的 NestJS 应用程序创建一个物化视图。数据库是Postgres。

不幸的是,查看实体不符合要求:https ://www.bookstack.cn/read/TypeORM/view-entities.md

期望的行为:就像模型一样,在 NestJS 项目中定义了物化视图,并带有选项 'synchronize:true' :如果视图不存在,则项目会在运行时创建视图,如果存在,则仅与其同步(就像模型一样)。

有任何线索可以帮助我实现这一目标吗?

typeorm nestjs

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