小编Jos*_*san的帖子

@Query() 不会转换为 DTO

我有一个控制器需要在请求查询字符串中接收数据(我无法使用主体,因为我正在与旧系统交互)。

我写了一个 DTO 映射查询参数到一个对象,我正在使用 ValidationPipe 来验证数据并将其转换为我的 DTO。

所以,我有这个:

import { Get, Controller, Query, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';

class TestDto {
  @IsNumber()
  field1: number;
  @IsBoolean()
  field2: boolean;
}

@Controller()
export class AppController {
  constructor() {}

  @Get()
  @UsePipes(new ValidationPipe({ whitelist: false, transform: true}))
  root(@Query() dto: TestDto): TestDto {
    return dto;
  }

}
Run Code Online (Sandbox Code Playgroud)

所有以前的代码都编译并遵循 NestJS 文档,但是当我调用http://localhost:3000/?field1=15&field2=true 时,我得到了这个:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": [
        {
            "target": {
                "field1": "15",
                "field2": "true"
            },
            "value": "15",
            "property": "field1",
            "children": …
Run Code Online (Sandbox Code Playgroud)

nestjs

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

诗乃:强制回拨电话

我正在用这段代码测试一个函数:

return new Promise((ok, fail) => {
  this.repository.findById(id, (error, result) => {
    if (error)
      return fail(error);
    ok(result);
  });
});
Run Code Online (Sandbox Code Playgroud)

我想测试失败的路径,即当findById方法调用带有错误的回调时.我正在使用sinon为我repository及其findById方法生成存根,但我不知道如何强制存根使用所需参数调用回调

以前有人这样做过吗?

谢谢

node.js sinon

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

架构服务器端i18n的最佳方法

我正在使用nestjs创建我的REST API,并且我要求为API返回的所有消息(异常消息,提示等)支持i18n,我想知道这样做的更好方法是什么使用nestjs框架。

使用Plain Express,我可以从请求标头中获取用户语言,然后可以将其翻译为Nestjs中间件,以便将语言代码放入存在于请求执行上下文中的某种软件中,然后从我的i18n服务中使用(不想在每个软件中都添加语言参数,我需要用户语言)您如何看待?解决我的需求是否合适?在当前请求中放置语言的最佳位置是哪一个?

nestjs

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

使用NestJS测试猫鼬模型

我使用的是NestJS的mongoose模块,所以我有模式和接口,在服务中,我使用@InjectModel注入模型。我不知道如何模拟要注入服务的模型。

我的服务如下所示:

    @Injectable()
    export class AuthenticationService {

        constructor(@InjectModel('User') private readonly userModel: Model<User>) {}

        async createUser(dto: CreateUserDto): Promise<User> {
            const model = new this.userModel(dto);
            model.activationToken = this.buildActivationToken();
            return await model.save();
          }
    }
Run Code Online (Sandbox Code Playgroud)

在我的服务测试中,我有这个:

    const mockMongooseTokens = [
      {
        provide: getModelToken('User'),
        useValue: {},
      },
    ];

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

        service = module.get<AuthenticationService>(AuthenticationService);
      });
Run Code Online (Sandbox Code Playgroud)

但是当我运行测试时,我得到了这个错误:

    TypeError: this.userModel is not a constructor
Run Code Online (Sandbox Code Playgroud)

我也想让我的模型对其执行单元测试,如本文所示

nestjs

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

标签 统计

nestjs ×3

node.js ×1

sinon ×1