标签: nestjs

如何过滤掉多余的模型属性

我有一个像这样的 DTO 对象:

export class CreateProductDTO {
  readonly _id: number;
  readonly _name: string;
  readonly _price: number;
}
Run Code Online (Sandbox Code Playgroud)

我的 post 方法中使用了 DTO

@Post('users')
async addUser(@Response() res, @Body(new ValidationPipe()) createUserDTO: CreateUserDTO) {
    await this.userService.addUser(createUserDTO).subscribe((users) => {
        res.status(HttpStatus.OK).json(users);
    });
}
Run Code Online (Sandbox Code Playgroud)

当我发布 json 数据时,它将序列化为 CreateProduceDTO obcjet

{
  "_id":1,
  "_name":"Lux",
  "_age":19
}
Run Code Online (Sandbox Code Playgroud)

但我发布带有多余属性的 json 数据,它也序列化为带有多余属性的 CreateProduceDTO obcjet

{
  "_id":1,
  "_name":"Lux",
  "_age":19,
  "test":"abcv"
}

CreateUserDTO { _id: 1, _name: 'Lux', _age: 19, test: 'abcv' }
Run Code Online (Sandbox Code Playgroud)

我曾尝试用管道过滤它,但我不知道。谢谢大家。

node.js typescript nestjs

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

Nest 无法解析 AuthService 的依赖关系

我正在关注此处提供的文档

https://docs.nestjs.com/techniques/authentication#jwt-functionality

为了获得更快的支持,我创建了一个有问题的 git 存储库

https://github.com/Sano123456/nestjs-jwt

node -v -> v10.15.2
npm -v -> 6.14.6
nest -v -> 7.4.1
Run Code Online (Sandbox Code Playgroud)

第一个问题: 在 AuthModule 中,如果我按照文档中的说明进行操作并只导入 UserModule,它会返回 UserModule 和 AuthModule 之间循环依赖的错误

@Module({
  imports:[
    UsersModule,
    PassportModule
  ],
  providers: [AuthService],
  controllers: [AuthController],
  exports:[AuthService, LocalStrategy]
})
export class AuthModule {}
Run Code Online (Sandbox Code Playgroud)

错误:

[ExceptionHandler] Nest cannot create the AuthModule instance.
The module at index [0] of the AuthModule "imports" array is undefined.

Potential causes:
- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency
- …
Run Code Online (Sandbox Code Playgroud)

nestjs nestjs-passport nestjs-jwt

2
推荐指数
3
解决办法
3475
查看次数

无法在节点中导入 ESM .ts 模块

我一直在尝试在 nodejs 中导入一个用 typescript 编写的 ESM 模块。但我收到以下错误:

An import path cannot end with a '.ts' extension.
Run Code Online (Sandbox Code Playgroud)

实用程序

 export class Util {
    constructor ( ) {
       
    }
      log(msg) {
        console.log(msg) 
    }
  }
Run Code Online (Sandbox Code Playgroud)

索引.ts

import {log} from './Util.ts'
log(task.query.criteria, payload.parameters)
Run Code Online (Sandbox Code Playgroud)

我也在"type":"module"里面添加了package.json

我将 .ts 更改为 .js 只是为了看看它是否有效,然后我得到:

Object.defineProperty(exports, "__esModule", { value: true });                         ^

ReferenceError: exports is not defined
at file:///C:/Users/abc/NestJsPOC/NestPOC/dist/main.js:2:23
Run Code Online (Sandbox Code Playgroud)

配置文件

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": …
Run Code Online (Sandbox Code Playgroud)

javascript node.js typescript ecmascript-6 nestjs

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

如何在一个 DTO 中编写 @Param 和 @Body

我正在使用 nestjs 并且我努力使用 DTO 并生成这样的 update-todo.dto.ts。

如何在一个 DTO 中同时使用 @Param 和 @Body?

@Param('id') id: string,
@Body('status') status: TodoStatus
Run Code Online (Sandbox Code Playgroud)

那么如何转换我的代码?

import { TodoStatus } from '../todo.model';
export class UpdateTodoDto {
  id: string;
  status: TodoStatus;
}
Run Code Online (Sandbox Code Playgroud)
  @Patch('/:id/status')
  updateTodoStatus(
    @Param('id') id: string,
    @Body('status') status: TodoStatus
    // convert this line
  ): Todo {
    return this.todosService.updateTodoStatus(id, status);
  }
Run Code Online (Sandbox Code Playgroud)

dto nestjs

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

类转换器未转换为数字数组

我有一个 DTO,其中有一个字段,它是一个数字数组。这些 id 来自 API 查询参数。我正在使用 Class Transformer 将这些 id 转换为数字数组。但我只得到一个字符串数组。我的 DTO 课程如下。

export class EvseGetQueryDto {
  ...
  ...

  @IsOptional()
  @IsArray()
  @IsNumber({}, {each: true})
  @ApiProperty({ type: [Number] })
  @Type(() => Number)
  locations?: number[];

  ...
  ...
}
Run Code Online (Sandbox Code Playgroud)

我的控制器代码如下所示。

async GetAll(@Query() query: EvseGetQueryDto): Promise<EvseDto[]> {
    return await this.evseService.GetAll(query);
}
Run Code Online (Sandbox Code Playgroud)

如果我像下面这样调用我的控制器,我仍然['1', '2']在我的位置字段中。

http://localhost:3000/evses?locations[]=1&locations[]=2
Run Code Online (Sandbox Code Playgroud)

任何人都可以指导我吗?

typescript class-validator nestjs class-transformer

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

区分控制器的2条路由(NestJS)

编辑:当我将 @Get('/random') 移动到其他 2 条路线上方时,它正在工作......很奇怪

我正在做一个 NestJS 服务器,它只获取 Breaking Bad API 的一些路由并在服务器的路由中显示 JSON,

我想创建 3 条路线:

  • 1 返回节目所有字符的 JSON (/characters/all)
  • 1 返回显示的单个字符的 JSON (/characters/:id)
  • 1 返回节目随机字符的 JSON (/character/random)

两个第一条路线正在运行,但我无法获得最后一条路线, 我收到错误 500,显示错误:请求失败,状态代码为 500,目标网址为“https://www.breakbadapi.com/api/”字符/随机”,我不知道为什么是“字符”而不是“字符”

这是我的代码:

characters.controller.ts

import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import { CharactersService } from './characters.service';

@Controller('characters')
export class CharactersController {
    constructor(private readonly charactersService: CharactersService) {}

    @Get('/all')
    getAll() {
        return this.charactersService.getAll();
    }

    @Get(':id')
    getOne(@Param('id') id: string) {
        return this.charactersService.getOne(id);
    }

    @Get('/random')
    getRandom() {
        return …
Run Code Online (Sandbox Code Playgroud)

javascript node.js nestjs

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

Nestjs 循环依赖 forwardRef() 的缺点

官方循环依赖说:

当两个类相互依赖时,就会发生循环依赖。例如,A 类需要 B 类,B 类也需要 A 类。在 Nest 中,模块之间和提供者之间可能会出现循环依赖。

虽然应该尽可能避免循环依赖,但你不能总是这样做。

不使用的原因是什么forwardRef()

circular-dependency nestjs

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

Nestjs:导入模块未定义,但可以导入模块中的方法和函数

我正在使用NestjsWebStorm & TS 4.2.3^latest。

我面临的问题有点奇怪。例如,一些模块axios可以像往常一样安装、导入和使用。但是有些模块,尤其是 Nodejs Core,比如fspath,不能作为模块导入。但是他们的方法可以导入和使用就好了!

//ERROR: Module undefined on run:dev, but no error in IDE
import path from 'path';
import fs from 'fs';

//Working fine
import { join } from 'path';
import { readFileSync } from 'path';
Run Code Online (Sandbox Code Playgroud)

我敢肯定,他们有正确的 TS 类型,甚至手动安装。例如:

import axios from 'axios';
import path from 'path'; //path is undefined
import { join } from 'path'; // working fine
import { Injectable } from '@nestjs/common';

@Injectable() …
Run Code Online (Sandbox Code Playgroud)

node.js webstorm typescript ts-node nestjs

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

在 NestJS 中连接后,Socket.io 客户端断开连接

我正在尝试使用 nestjs 创建聊天,但它的问题在于@SubscribeMessage()连接的实现正在工作,但是当我尝试侦听来自前端的发射和consolenestjs 中的数据时,它不起作用

import { Server, Socket } from 'socket.io';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../entities/user.entity';
import { Repository } from 'typeorm';
import { Messenger } from './entities/messenger.entity';

@Injectable()
@WebSocketGateway(5000)
export class MessengerGateway implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(Messenger)
    private messageRepository: Repository<Messenger>,
  ) {}

  @SubscribeMessage('loadPeople')
  handleEvent(client: Socket, data){
    console.log(data);
    // this is not working
  }

  async afterInit(server: Server) …
Run Code Online (Sandbox Code Playgroud)

websocket socket.io reactjs nestjs nestjs-gateways

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

Nest.js 测试错误:Nest v8 中不允许使用“extends Logger”指令。请改用“扩展 ConsoleLogger”

这是我遇到的问题:

我在 Nest.js 中使用我的自定义记录器:

export class ReportLogger extends ConsoleLogger {
  verbose(message: string) {
    console.log('?Verbose?Reporting', message);
    super.verbose.apply(this, arguments);
  }

  log(message: string) {
    console.log('?Log?Reporting', message);
    super.log.apply(this, arguments);
  }
}
Run Code Online (Sandbox Code Playgroud)

log.interceptor.ts文件:

export class LogInterceptor implements NestInterceptor {
  constructor(private reportLogger: ReportLogger) {
    this.reportLogger.setContext('LogInterceptor');
  }

  intercept(context: ExecutionContext, next: CallHandler) {
    const http = context.switchToHttp();
    const request = http.getRequest();

    const now = Date.now();
    return next
      .handle()
      .pipe(
        tap(() =>
          this.reportLogger.log(
            `${request.method} ${request.url} ${Date.now() - now}ms`,
          ),
        ),
      );
  }
}
Run Code Online (Sandbox Code Playgroud)

这是main.ts文件:

async …
Run Code Online (Sandbox Code Playgroud)

testing node.js e2e-testing nestjs

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