0

I need to validate an object where each key is an enum and each value have the same shape.

Right now I was able to validate the object by explicitly setting each key and validate each nested object, but I would like something more usable so when I need to change the enum I don't have to update the dtos too.

This is the enum I would like to use

enum Countries {
  ES = 'ES',
  IT = 'IT'
}

This is my actual work.

class Country {
  @IsString({ each: true })
  @IsOptional()
  readonly region?: string[];

  @IsString({ each: true })
  @IsOptional()
  readonly province?: string[];

  @IsString({ each: true })
  @IsOptional()
  readonly zipcode?: string[];
}

class Locations {
  @IsObject()
  @ValidateNested()
  @Type(() => Country)
  @IsOptional()
  readonly ES?: Country;
  
  @IsObject()
  @ValidateNested()
  @Type(() => Country)
  @IsOptional()
  readonly IT?: Country; 
}

export class CreateDto {
  ... other props
  
  @IsObject()
  @ValidateNested()
  @Type(() => Locations)
  @IsOptional()
  readonly locations?: Locations;
}

As you can see if I add a new country to the enum I have to update the class Locations with the corresponding prop.

## Example Payload
{
  ... other props

  locations: {
    IT: {
      region: ['Lazio']
    }
  }
}
fasenderos
  • 388
  • 3
  • 18

1 Answers1

0

Data structures that frequently need to change keys are not good. I think the data structure should be designed like this:

enum Country {
  ES = 'ES',
  IT = 'IT'
}

class Location {
  @IsEnum(Country)
  country: Country;

  @IsString({ each: true })
  @IsOptional()
  readonly region?: string[];

  @IsString({ each: true })
  @IsOptional()
  readonly province?: string[];

  @IsString({ each: true })
  @IsOptional()
  readonly zipcode?: string[];
}

export class CreateDto {
  ... other props
  
  @ValidateNested({ each: true })
  @Type(() => Location)
  @IsOptional()
  readonly locations?: Location[];
}
Cody Tseng
  • 190
  • 4