CON-1508: Decorator based arguments validation approach#105
CON-1508: Decorator based arguments validation approach#105PavelLoparev wants to merge 1 commit intomasterfrom
Conversation
| @Validate | ||
| async getProjectDetails(@IsNotEmpty projectId: string): Promise<ProjectDto> { |
There was a problem hiding this comment.
@dimitrystd it's just an example of how it can be used (SUBM api class is in private sdk)
There was a problem hiding this comment.
Looks interesting. Just two concerns:
- It only works with simple types. If we pass an object of
Parametersclass then we can't validate it. Or need to write more code.
Using!and strict compilation can give us similar results. - We implement just another validation package.
There was a problem hiding this comment.
We would need to refactor here and there to support strictNullChecks mode.
| export function IsNotEmpty( | ||
| target: any, | ||
| methodName: string, | ||
| parameterIndex: number | ||
| ) { | ||
| if (!target?.validations) { | ||
| target.validations = []; | ||
| } | ||
|
|
||
| target.validations.push(`${methodName}:${parameterIndex}:${IsNotEmpty.name}`); | ||
| } |
There was a problem hiding this comment.
Registers validation for argument (it's not possible to get value of the argument in an argument decorator which is weird)
| function IsNotEmptyValidate( | ||
| methodName: string, | ||
| argumentIndex: number, | ||
| argumentValue: any | ||
| ) { | ||
| if (argumentValue === '' || argumentValue === null || argumentValue === undefined) { | ||
| throw new Error(`Invalid empty argument at index ${argumentIndex} with "${argumentValue}" value in "${methodName}" method`); | ||
| } | ||
| } |
There was a problem hiding this comment.
Actual validation logic
| for (const validation of target.validations) { | ||
| const [methodName, argumentIndex, validatorName] = validation.split(":"); | ||
|
|
||
| if (method.name === methodName) { | ||
| switch (validatorName) { | ||
| case IsNotEmpty.name: | ||
| const argumentValue = args[argumentIndex]; | ||
|
|
||
| IsNotEmptyValidate(methodName, argumentIndex, argumentValue); | ||
|
|
||
| break; | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Walk through registered validations and execute them
|
We decided to move this approach directly to the class-validator lib (typestack/class-validator#2432). If it will be accepted there we will get back to this ticket. |
Arguments decorator-based validation approach:
IsNotEmptyargument decorator "registers" validation in the target object (just an array of strings like<methodName>:<parameterIndex>:<validatorName>)Validationmethod decorator reads all registered validations and executes them.This scheme with 2 decorators instead of just one argument decorator is only needed because argument level decorator can't access actual argument value (it's weird)
Usage example:
As I get it I can't use
class-validatorlib because it's only for class property validations, not method arguments.