禁止 Nestjs 中 DTO 的特定枚举值 [英] Forbid specific enum value for DTO in Nestjs

查看:192
本文介绍了禁止 Nestjs 中 DTO 的特定枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的AppState"枚举具有以下可能的枚举值:

My "AppState" enum has following possible enum values:

export enum AppState {
  SUCCESS,
  ERROR,
  RUNNING
}

我有一个带有 appStateUpdateAppStateDTO,它应该接受除 RUNNING 之外的每个枚举值.

I have a UpdateAppStateDTO with an appState which should accept every enum value except RUNNING.

export class UpdateAppStateDTO {
  @IsEnum(AppState)
  @NotEquals(AppState.RUNNING) // Doesn't work properly
  public appState: AppState;
}

对于路线我有这个例子

  @Patch()
  public setState(@Body() { appState }: UpdateAppStateDTO): void {
    console.log(appState);
  }

如果请求有一个空的正文或一个无效的枚举值,比如 appState 的foobar",我得到 400,这很好.

If the request has an empty body or a non valid enum value like "foobar" for appState I'm getting a 400, which is fine.

问题是当我发送RUNNING"时,我仍然得到 200 而不是 400.

The problem is that when I send "RUNNING" I'm still getting a 200 instead of a 400.

如何防止这种行为?

推荐答案

我假设您发送的是字符串 'RUNNING',并且您正试图确保这不是用过,对吗?使用您目前所拥有的,您的枚举映射到这些值:

I assume you are sending in the string 'RUNNING', and you're trying to make sure that that is what is not used, correct? With what you've currently got, your enum maps to these values:

export enum AppState {
  SUCCESS = 0,
  ERROR = 1,
  RUNNING = 2
}

因此,如果您发送字符串 'RUNNING',验证器会检查 RUNNING !== 2 实际上是 true 前导成功验证.@IsEnum() 装饰器检查在枚举的有效键中发送的值,因此发送 'RUNNING' 通过该检查,因此您为什么不在那里得到某种错误.

So if you send in the string 'RUNNING', the validator checks that RUNNING !== 2 which is in fact true leading to successful validation. The @IsEnum() decorator checks that the value sent in in a valid key of the enum, so sending in 'RUNNING' passes that check, hence why you don't get some sort of error there.

解决此问题的最详细方法是使您的枚举成为 string enum,如下所示:

The most verbose way to fix this is to make your enum a string enum like so:

export enum AppState {
  SUCCESS = 'SUCCESS',
  ERROR = 'ERROR',
  RUNNING = 'RUNNING'
}

这将使每个 AppState 值映射到其相应的字符串,尽管这确实导致必须键入大量声明并可能导致重复代码.另一种管理方法是将您的 @NotEquals() 枚举设置为枚举值提供的键,如下所示:

This will make each AppState value map to its corresponding string, though that does lead to having to type out a lot of declarations and can lead to duplicate code. Another way to mange this is to set your @NotEquals() enum to the key provided by the enum value like so:

export class UpdateAppStateDTO {
  @IsEnum(AppState)
  @NotEquals(AppState[AppState.RUNNING])
  public appState: AppState;
}

但请记住,使用这种方法,当您稍后查看 appState 时,它仍然是数值而不是字符串.

But keep in mind that with this approach when you look at appState later it will still be a numeric value instead of a string.

您可以尝试使用 这个 stackblitz 我为此制作的一些正在运行的代码.

You can play around with this stackblitz I made for this to see some running code.

这篇关于禁止 Nestjs 中 DTO 的特定枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆