Nest.js validate: strings[] | string (union type)

Viewed 190

I have two APIs, one has rest client that makes requests to the other and I would like to validate the api error it receives.

The api error signature is (in typescript):

class ApiError {
  error?: string;
  message: string | string[];
  statusCode: number;
}

Now what I have trouble validating is the message, it is a union type of string and array of string. I want to know if there is some way to validate it using the @nestjs/class-validator library. Something like:

class ExternalApiErrorDto {
  @IsString()
  @IsOptional()
  error?: string;
  message: string | string[];
  @IsPositive()
  statusCode: number;
}
1 Answers

I end up transforming the expected message into an array and validating if it's an array of strings by doing the following:

export class ExternalApiErrorDto {
  @IsString()
  @IsOptional()
  error?: string;
  @Transform(({ value }) => (Array.isArray(value) ? value : [value]))
  @IsString({ each: true })
  message: string[];
  @IsPositive()
  statusCode: number;
}

Either way, it would be great to know how to validate a union type. One possibility could perhaps be to use a custom validator, implementing ValidatorConstraintInterface.

Related