Recently, I've been working on enhancing my validation middleware to accommodate for both classes (any) and arrays (any[]) as input. Initially, this middleware was set up to take in a single class type as an input parameter. However, I managed to modify it successfully to accept array types as well. The hiccup came when I attempted to allow for both class and array types simultaneously.
import { plainToClass } from 'class-transformer';
import { validate, ValidationError } from 'class-validator';
const validateType = (
type: any | any[],
value: string,
): void => {
validate(plainToClass(type, value), { }).then((errors: ValidationError[]) => {
if (errors.length > 0) {
console.log(`Errors found`);
} else {
console.log(`Success`);
}
});
When passing a class as input, the function compiles successfully. However, it fails when an array is provided as input;
class CreateObjectDto {
public a: string;
public b: string;
}
const inputString = "{a: \"something\", b: \"else\"}"
const inputArray = "[{a: \"something\", b: \"else\&\quot;}], [{a: \"another\", b: \"more\"}]"
validateType(CreateObjectDto, inputString); // pass
validateType(CreateObjectDto, inputArray); // fail
By modifying the function signature to only accept arrays (type: any[]), the function runs without any issues. However, I'm struggling to find a way to specify the input type as either a single class or an array of classes.
I am open to suggestions on how to declare CreateObjectDto[] as an input parameter for the function. Alternatively, I'd appreciate any insights on adjusting the function signature to effectively distinguish between a single class and an array of classes within the input string.
Thank you!