转换请求体中的属性

huangapple go评论59阅读模式
英文:

Transform attributes in request body

问题

I have used @Transform decorator from class-transformer to sanitize specific fields in user input.

import { IsString } from "class-validator";
import { Transform } from "class-transformer";

export class SearchRequestDto {
  @Transform((data) => data.value && sanitizeRegex(data.value))
  @IsString()
  readonly term: string = '';
}

如何创建一个新的装饰器以更直接地将此转换器添加到 DTO,就像这样:

export class SearchRequestDto {
  @Regex()
  @IsString()
  readonly term: string = '';
}
英文:

I have used @Transform decorator from class-transformer to sanitize specific fields in user input.

import { IsString } from "class-validator";
import { Transform } from "class-transformer";

export class SearchRequestDto {
  @Transform((data) => data.value && sanitizeRegex(data.value))
  @IsString()
  readonly term: string = '';
}

How can I create a new decorator to add this transformer to DTO more straight forward. Like this:

export class SearchRequestDto {
  @Regex()
  @IsString()
  readonly term: string = '';
}

答案1

得分: 1

你可以创建一个自定义装饰器,类似于这样:

export const Regex = () => Transform((data) => data.value && sanitizeRegex(data.value))

然后按照你想要的方式使用它:

export class SearchRequestDto {
  @Regex()
  @IsString()
  readonly term: string = '';
}
英文:

You can create a Custom Decorator that looks like this:

export const Regex = () => Transform((data) => data.value && sanitizeRegex(data.value))

And then use it the way you wanted:

export class SearchRequestDto {
  @Regex()
  @IsString()
  readonly term: string = '';
}

huangapple
  • 本文由 发表于 2023年4月19日 18:33:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76053487.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定