Skip to content

Commit

Permalink
feat(stark-core): add new StarkArrayIsValid validation decorator
Browse files Browse the repository at this point in the history
This new validator validates each value contained in the array.
This replaces the not properly working `ValidateNested()` decorator.
  • Loading branch information
SuperITMan committed Mar 12, 2024
1 parent 3205bfc commit 8560439
Show file tree
Hide file tree
Showing 5 changed files with 142 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { ArrayNotEmpty, IsDefined, IsNotEmpty, IsString, ValidateNested } from "class-validator";
import { ArrayNotEmpty, IsDefined, IsNotEmpty, IsString } from "class-validator";
import { autoserialize } from "cerialize";

import { StarkApplicationMetadata } from "./application-metadata.entity.intf";
import { StarkLanguageImpl } from "../language";
import { StarkLanguage } from "../language/language.entity.intf";
import { StarkLanguages } from "../language/language.constants";
import { StarkArrayIsValid } from "../../../validation/decorators";

/**
* This class is only for serialization purposes
Expand Down Expand Up @@ -45,7 +46,7 @@ export class StarkApplicationMetadataImpl implements StarkApplicationMetadata {

@IsDefined({ groups: ["settings"] })
@ArrayNotEmpty({ groups: ["settings"] })
@ValidateNested({ groups: ["settings"], each: true }) // validate each item of the array
@StarkArrayIsValid({ groups: ["settings"] })
public supportedLanguages: StarkLanguageImpl[] = [];

/**
Expand Down
1 change: 1 addition & 0 deletions packages/stark-core/src/validation/decorators.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from "./decorators/array-is-valid";
export * from "./decorators/is-bban";
export * from "./decorators/is-bic";
export * from "./decorators/is-company-number";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./array-is-valid/array-is-valid.validator.decorator";
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { MaxLength, validateSync, ValidationError } from "class-validator";
import { StarkArrayIsValid, starkArrayIsValidValidatorName } from "./array-is-valid.validator.decorator";

class ValueClass {
@MaxLength(10)
public description!: string;
}

class MyClass {
@StarkArrayIsValid()
public dummyArray: (ValueClass | string)[] = [];
}

class SimpleClass {
@StarkArrayIsValid()
public name!: string;
}

describe("ValidatorDecorator: StarkArrayIsValid", () => {
let myClass: MyClass;
let simpleClass: SimpleClass;
let valueClass: ValueClass;
const validatorConstraintName: string = starkArrayIsValidValidatorName;

beforeEach(() => {
myClass = new MyClass();
simpleClass = new SimpleClass();
valueClass = new ValueClass();
});

it("should fail if the object to validate is not an Array", () => {
const errors: ValidationError[] = validateSync(simpleClass);

expect(errors.length).toBe(1);
expect(errors[0].constraints).toBeDefined();
expect(errors[0].constraints![validatorConstraintName]).toBeDefined();
});

it("should fail if Array contains invalid values", () => {
valueClass.description = "this is not a valid length";
myClass.dummyArray.push(valueClass);
const errors: ValidationError[] = validateSync(myClass);

expect(errors.length).toBe(1);
expect(errors[0].constraints).toBeDefined();
expect(errors[0].constraints![validatorConstraintName]).toBeDefined();
expect(errors[0].constraints![validatorConstraintName]).toContain("array values");
});

it("should NOT fail if Array contains valid values", () => {
valueClass.description = "length ok";
myClass.dummyArray.push("stringValue");
const errors: ValidationError[] = validateSync(myClass);

expect(errors.length).toBe(0);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import {
registerDecorator,
validateSync,
ValidationError,
ValidationOptions,
ValidatorConstraint,
ValidatorConstraintInterface
} from "class-validator";
import { StarkValidationErrorsUtil } from "../../../util/validation-errors.util";

/**
* Name of the validator, in case injection is needed.
*/
export const starkArrayIsValidValidatorName = "starkArrayIsValid";

/**
* StarkArrayIsValid validator constraint
* Validates that all entries in the Array are valid (validateSync is called in every value)
*/
@ValidatorConstraint({ name: starkArrayIsValidValidatorName, async: false })
class StarkArrayIsValidConstraint implements ValidatorConstraintInterface {
/**
* an Array of validation errors' values
*/
public valuesValidationErrors: ValidationError[] = [];

/**
* Validates that a give Array is valid
* @param array - the array to validate
* @returns `true` if the array is valid
*/
public validate(array: any[]): boolean {
if (!array || !Array.isArray(array) || array.length === 0) {
return false;
}

this.valuesValidationErrors = [];

array.forEach((value: any) => {
// skipping primitive types
if (typeof value === "object") {
this.valuesValidationErrors = [...this.valuesValidationErrors, ...validateSync(value)];
}
});

return this.valuesValidationErrors.length === 0;
}

/**
* Default message displayed when the array contains invalid entries
* @returns A default message
*/
public defaultMessage(): string {
let valuesValidationMessage: string = StarkValidationErrorsUtil.toString(this.valuesValidationErrors);

if (valuesValidationMessage.length) {
valuesValidationMessage = "\nValidation errors in $property array values:\n\n" + valuesValidationMessage;
}

return "$property array contains invalid entries.\n" + valuesValidationMessage;
}
}

/**
* Validator decorator that uses the StarkArrayIsValid validator constraint
* @param validationOptions - options to determine if the array is valid
* @returns Function
*/
export function StarkArrayIsValid(validationOptions?: ValidationOptions): Function {
return (object: object, propertyName: string): void => {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: [],
validator: StarkArrayIsValidConstraint
});
};
}

0 comments on commit 8560439

Please sign in to comment.