简体   繁体   中英

DRY principles in NestJS entities with typeorm and class-validator

Is there a way to turn this code

export class person {
  @IsString()
  @Column('text')
  name: string

  @IsOptional()
  @IsString()
  @Column('text')
  description?: string
}

Into something that resembles this

export class person {
  name: string
  description?: string
}

I'm aware that decorators are needed, but SSOT seems lost when property type has to be declared three times or more per property.

Is there an easier way around this? JOI? Schema generation?

If you find yourself using the same set of Decorators over and over on properties you could create a new Decorator that just composes them together.

const CombinedDecorator = (target, property, descriptor) => {
   IsOptional(target, property, descriptor);
   IsString(target, property, descriptor);
   Column('text')(target, property, descriptor);
}

class Person {
   @CombinedDecorator()
   name: string;
}

You could either come up with a few of these that cover your common use cases or consider turning it into a Decorator Factory that takes in a config object and optionally applies decorators based on the params.

I think that even a little bit of repetition with decorators is much preferable to using something like JOI as you'll still have to explicitly state all the rules but in a place separate from your actual models which allows for multiple sources of truth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM