英文:
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 = '';
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论