Skip to content

✨ Adding validations #2285

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -969,7 +969,15 @@ export class ExperimentController {

@Post()
public create(
@Body({ validate: true }) experiment: ExperimentDTO,
@Body({
validate: {
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
},
transform: { enableImplicitConversion: true },
})
experiment: ExperimentDTO,
@CurrentUser() currentUser: UserDTO,
@Req() request: AppRequest
): Promise<ExperimentDTO> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ export class MoocletPolicyEditorComponent implements OnInit {
assignmentAlgorithm: this.currentAssignmentAlgorithm,
...jsonValue,
};
const DTOInstance = plainToInstance(ValidatorClass, plainDTO);
return from(validate(DTOInstance));
const DTOInstance = plainToInstance(ValidatorClass, plainDTO, { enableImplicitConversion: true });
return from(validate(DTOInstance, { whitelist: true, forbidNonWhitelisted: true, forbidUnknownValues: true }));
}

// Method to get current editor value for parent components
Expand Down
63 changes: 51 additions & 12 deletions types/src/Mooclet/MoocletTSConfigurablePolicyParametersDTO.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,78 @@
import { IsNumber, IsString, ValidateNested, IsOptional, IsObject, IsDefined, IsNotEmpty } from 'class-validator';
import { Type } from 'class-transformer';
import {
IsNumber,
IsString,
ValidateNested,
IsOptional,
registerDecorator,
IsDefined,
IsNotEmpty,
ValidationOptions,
validate as CVValidate,
validateSync as CVValidateSync,
} from 'class-validator';
import { plainToClass, Type } from 'class-transformer';
import { MoocletPolicyParametersDTO } from './MoocletPolicyParametersDTO';

export class Prior {
@IsDefined()
@IsNumber()
@Type(() => Number)
failure = 1;
failure: number;

@IsDefined()
@IsNumber()
@Type(() => Number)
success = 1;
success: number;
}

export class CurrentPosteriors {
@IsDefined()
@IsNumber()
@Type(() => Number)
failures: number;

@IsDefined()
@IsNumber()
@Type(() => Number)
successes: number;
}

const IsCurrentPosteriorsRecord = (validationOptions?: ValidationOptions) => {
return function (object: unknown, propertyName: string) {
registerDecorator({
name: 'IsCurrentPosteriorsRecord',
target: object.constructor,
propertyName: propertyName,
constraints: [],
options: {
message: ({ value }) => {
const errors = Object.values(value).map((val) => {
const instance = plainToClass(CurrentPosteriors, val);
return CVValidateSync(instance);
});
// Flat the array of arrays
return errors.reduce((acc, val) => acc.concat(val), [])[0].toString();
},
...validationOptions,
},
validator: {
async validate(value: unknown) {
return Promise.all(
Object.values(value).map(async (val) => {
const instance = plainToClass(CurrentPosteriors, val);
return await CVValidate(instance).then((errors) => errors.length === 0);
})
).then((values) => values.every((val) => val));
},
},
});
};
};

export class MoocletTSConfigurablePolicyParametersDTO extends MoocletPolicyParametersDTO {
@IsDefined()
@ValidateNested()
@Type(() => Prior)
prior: Prior = new Prior();
prior: Prior;

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without the default values for prior and it's properties, the frontend can't create a default object, the priors as "prior": { "success": 1, "failure": 1 } should show up here in the editor.

image

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The validation isn't quite working for me on the frontend when I fill in prior manually either, it allows me to hit "next" with an object like below. It does catch it on submit and give correct message, however the other validations will raise an error immediately as the user types.

{
"prior": {
"success": "d",
"failure": 2
},

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should not add the default values in the class constructor because class transform uses this class constructor to create the definition and assign the object (to be tested) to the constructed object. If we are adding the default values, the constructor definition also contains the value which we don't want.
For testing, add the default value for Prior in the types
Remove the "prior": { "success": 1, "failure": 1}.
It will not throw an error.

I can add the appropriate config for the frontend side for validation to work correctly.

@IsOptional()
@IsObject()
@ValidateNested({ each: true })
@Type(() => CurrentPosteriors)
@IsCurrentPosteriorsRecord()
current_posteriors?: Record<string, CurrentPosteriors>;

@IsNumber()
Expand Down
Loading