标签: nestjs

如何使用 Nest.js 中的类验证器验证数组中每个对象的字段

import { ArrayMaxSize, ArrayMinSize, IsArray, IsBoolean, IsString, ValidateNested } from "class-validator";
import { Transform, Type } from "class-transformer";

class CreateAnswerDto {
  @IsBoolean()
  readonly isTrue: string;

  @IsString()
  title: string;

  @IsString()
  description: string;
}

const transformAnswers = answers => {
  return JSON.parse(answers.value);
};

export class CreateQuestionDto {
  @Transform(transformAnswers, { toClassOnly: true })
  @IsArray()
  @ArrayMinSize(4)
  @ArrayMaxSize(4)
  @ValidateNested({ each: true })
  @Type(() => CreateAnswerDto)
  readonly answers: CreateAnswerDto[];

  @IsString()
  readonly title: string;
}
Run Code Online (Sandbox Code Playgroud)

所以我有相同的代码,并且我想验证答案中的每个对象字段,但此代码不起作用。如果我发送了错误的数据,则此验证会跳过它。我怎样才能正确验证我的答案?

谢谢你的帮助!

javascript validation node.js class-validator nestjs

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

如何在 NestJS 中对 TypeORM 的自定义存储库进行单元测试?

要测试的类

我的 TypeORM 存储库extends AbstractRepository

@EntityRepository(User)
export class UsersRepository extends AbstractRepository<User> {

  async findByEmail(email: string): Promise<User> {
    return await this.repository.findOne({ email })
  }
}
Run Code Online (Sandbox Code Playgroud)

单元测试

describe('UsersRepository', () => {
  let usersRepository: UsersRepository

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [UsersRepository]
    }).compile()

    usersRepository = module.get<UsersRepository>(UsersRepository)
  })

  describe('findByEmail', () => {
    it(`should return the user when the user exists in database.`, async () => {
      const fetchedUser = await usersRepository.findByEmail('test1@test.com')
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

在这里,我收到错误:

TypeError: Cannot …
Run Code Online (Sandbox Code Playgroud)

unit-testing typescript jestjs typeorm nestjs

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

在没有前端的情况下从 firebase auth 模拟器获取用户的未签名令牌

我正在编写一个自定义后端(nestjs),其中我想验证来自 firebase auth 的令牌是否有效并检索用户信息。

我不想使用实际的 firebase 身份验证,因此我最终使用了 firebase 本地模拟器。

现在我想使用 postman 测试用 Nestjs 编写的端点,其中我从 postman 发送未签名的令牌以供 Nestjs 从本地模拟器进行验证。但我无法找到一种方法来创建未签名的令牌而不为其创建 UI,我真的不想花时间创建仅针对console.log令牌的反应应用程序。有没有更好的方法来做到这一点,我可能会错过?

谢谢您的帮助。

firebase firebase-authentication firebase-admin nestjs

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

如何避免 Nest.Js / Node.Js 进程占用 100% 的 CPU?

我有一个在 Nest.Js / Node.Js 上运行的应用程序,它执行文本处理,因此它有一个.map(或.forEach) 迭代,需要大量资源(标记一个句子,然后删除停用词等 \xe2\x80\ x94的每句话可能有几万个)。

\n

为了重现性,我提供了下面使用的代码,没有文本处理详细信息 \xe2\x80\x94 只是一个长而繁重的循环来模拟我的问题:

\n
  const before = Date.now() \n  const statements = [...Array(100)]\n  let l = 0\n  let p = 0\n  const processed = \n     statements.map((value, index) => {\n      \n         // a set of consecutive functions that take a long time to execute\n         for (let i = 0; i < 100000; i++) {\n              l = l + i * Math.random()\n         }\n         // console.log(index + \' \' + …
Run Code Online (Sandbox Code Playgroud)

javascript performance foreach node.js nestjs

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

我无法在 ubuntu 20.04 中安装 Nestjs

我正在使用 Ubuntu 20.04 LTS,我试图安装 Nestjs 来学习,但是......好吧,最好展示一下发生了什么

首先我尝试找出我的 npm 或 node 的版本,结果是:

$ npm - v

output: 6.14.16

$ node -v

output: v14.19.1
Run Code Online (Sandbox Code Playgroud)

理论上我可以安装nest,对吗?好吧,我运行了这段代码:

$ npm i -g @nestjs/cli

output: /home/user/.npm-global/bin/nest -> 
/home/user/.npm-global/lib/node_modules/@nestjs/cli/bin/nest.js
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.3.2 (node_modules/@nestjs/cli/node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

+ @nestjs/cli@8.2.3
updated 1 package in 17.045s
Run Code Online (Sandbox Code Playgroud)

我认为这个输出看起来很奇怪,尽管如此我还是试图发现 Nest 是否已安装

$ nest -v

output: Command 'nest' not found, did you mean:

  command 'newt' from snap newt …
Run Code Online (Sandbox Code Playgroud)

node.js npm nestjs ubuntu-20.04

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

在 NestJS 中,如何将令牌与使用 registerAsync 注册的模块关联起来?

我正在使用 NestJSCacheModule并使用它进行注册registerAsync,以便使用useFactory和注入配置模块。

我想提供一个特殊的令牌,因为我打算有多个缓存管理器。provide不支持使用registerAsync。我怎样才能实现这个目标?

代码示例:

import { CacheModule } from '@nestjs/common';
import { ENVALID } from 'nestjs-envalid';
import * as redisStore from 'cache-manager-redis-store';

export const CacheManager1 = CacheModule.registerAsync({
  provide: "CACHE_MANAGER_1", //this is not possible
  useFactory: async (env: EnvironmentConfig) => {
    return {
      ttl: env.MANAGER_ONE_TTL_SEC,
      store: redisStore,
      host: env.MANAGER_ONE_REDIS_HOST,
      port: env.MANAGER_ONE_REDIS_PORT,
      password: env.MANAGER_ONE_REDIS_PASSWORD,
      db: env.MANAGER_ONE_REDIS_DB,
    };
  },
  inject: [ENVALID],
});

Run Code Online (Sandbox Code Playgroud)

typescript nestjs

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

Is it possible to have multiple local strategies in passport implemented with NestJS

I have a scenario where I need to implement an authentication mechanism for admin and for normal users in my application using the Passport local strategy. I implemented the strategy for the normal users as described here. It is working perfectly fine.

However, now I need to implement the same local strategy for Admin login. I feel like it would have been much easier if both the type of users(admin and normal user) are on the same entity/table because …

passport-local passport.js nestjs

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

如果 nameOnly 设置为 true,mongoDB listCollections() 返回空

我正在使用 NestJS 尝试获取数据库下存在的集合列表。但是,如果我尝试使用该选项,{ nameOnly: true }我会得到一个空数组。

下面是我获取集合名称的代码:

  @Get(':client_name/listCollections')
  async collections(@Param('client_name') client_name) {
    let arrayOfCollections;
    const db = await this.databaseService.connectToDatabase(client_name);

    try {
      arrayOfCollections = await db
        .listCollections({ nameOnly: true })
        .toArray();
    } catch (error) {
      throw error;
    }
    if (arrayOfCollections) {
      return arrayOfCollections;
    }
  }
Run Code Online (Sandbox Code Playgroud)

如果我删除{ nameOnly: true },那么我会得到完整的列表,但由于这会锁定数据库并返回我不需要的额外信息,所以如果可能的话,我想避免使用它。

mongodb node.js nestjs

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

NestJs 中的 @Header('Cache-Control')

我有一个 NestJS REST api,并注意到 Cache-Control 标头未发送。我不确定我是否错过了 NestJS 的某些内容,但询问 google 如何使用 NestJS 缓存 REST API 获取响应只会引导我找到 NestJs 缓存管理器,该管理器位于内存缓存中的服务器上。所以我有几个问题:

  1. 缓存 REST API 数据响应不是很常见吗
  2. 我应该明确设置 @Header('Cache-Control', '..?')
  3. 也许在客户端缓存更好?(我知道数据有效性 - 数据不会改变我说的是文章)

感谢您的回答

caching browser-cache nestjs

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

类型错误:无法读取 NestJS 依赖注入上未定义的属性

我花了TypeError: Cannot read properties of undefined (reading 'create') at AuthenticationService.register很多时间阅读这个网站(和其他网站),试图找出我错过的内容。可能涉及 Typeorm 的是我知道我比 xe2 x80 x94 任何帮助都表示感谢。

\n

用户.module.ts

\n
import { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\nimport { User } from './user.entity';\nimport { UsersService } from './users.service';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([User])],\n  providers: [UsersService],\n  exports: [UsersService],\n})\nexport class UsersModule {}\n
Run Code Online (Sandbox Code Playgroud)\n

用户.service.ts

\n
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { CreateUserDto } from './dto/create-user.dto';\nimport { User } …
Run Code Online (Sandbox Code Playgroud)

typescript nestjs

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