[英]DRY principles in NestJS entities with typeorm and class-validator
有沒有辦法把這個代碼
export class person {
@IsString()
@Column('text')
name: string
@IsOptional()
@IsString()
@Column('text')
description?: string
}
變成類似這個的東西
export class person {
name: string
description?: string
}
我知道需要裝飾器,但是當每個屬性必須聲明屬性類型三次或更多時,SSOT似乎丟失了。
有沒有更簡單的方法可以解決此問題? JOI? 模式生成?
如果您發現自己一遍又一遍地在屬性上使用同一組Decorator,則可以創建一個將它們組合在一起的新Decorator。
const CombinedDecorator = (target, property, descriptor) => {
IsOptional(target, property, descriptor);
IsString(target, property, descriptor);
Column('text')(target, property, descriptor);
}
class Person {
@CombinedDecorator()
name: string;
}
您可以提出一些涵蓋您常用用例的方法,也可以考慮將其轉換成Decorator Factory,該Decorator Factory可以接受config對象,並可以選擇基於參數應用裝飾器。
我認為,與裝飾器進行一點重復比使用JOI之類的方法更可取,因為您仍然必須明確聲明所有規則,但要與實際模型分開,以允許多個事實來源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.