Created
October 20, 2021 11:37
-
-
Save siandreev/403b63911ef96ce1a5df0c4b6f2a65a3 to your computer and use it in GitHub Desktop.
ParameterDecorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Validator { | |
// Map<Class.prototype, Map<MethodName, IndexesToCheck>> | |
private static notEmptyValidatorMap: Map<Object, Map<string, number[]>> = new Map(); | |
static registerNotEmpty(target: Object, methodName: string, paramIndex: number): void { | |
let paramMap = this.notEmptyValidatorMap.get(target); | |
if (!paramMap) { | |
paramMap = new Map(); | |
this.notEmptyValidatorMap.set(target, paramMap); | |
} | |
let paramIndexes = paramMap.get(methodName); | |
if (!paramIndexes) { | |
paramIndexes = []; | |
paramMap.set(methodName, paramIndexes); | |
} | |
paramIndexes.push(paramIndex); | |
} | |
static performValidation(target: Object, methodName: string, paramValues: unknown[]): boolean { | |
const notEmptyMethodMap = this.notEmptyValidatorMap.get(target); | |
const paramIndexes = notEmptyMethodMap?.get(methodName); | |
if (!paramIndexes?.length) { | |
return true; | |
} | |
return paramValues.every((paramValue, index) => { | |
if (!paramIndexes.includes(index)) { | |
return true; | |
} | |
return paramValue != false; | |
}); | |
} | |
} | |
class Task { | |
@Validate | |
run(@NotEmpty name: string): void { | |
console.log("running task, name: " + name); | |
} | |
} | |
function Validate( | |
target: Object, | |
propertyKey: string, | |
descriptor: TypedPropertyDescriptor<any> | |
): TypedPropertyDescriptor<any> { | |
const originalMethod = descriptor.value; | |
descriptor.value = function (...args) { | |
if (!Validator.performValidation(target, propertyKey, args)) { | |
console.error('Validation failed, method call aborted:', | |
propertyKey); | |
return; | |
} | |
return originalMethod.apply(this, args); | |
} | |
return descriptor; | |
} | |
function NotEmpty(target: Object, propertyKey: string, parameterIndex: number) { | |
Validator.registerNotEmpty(target, propertyKey, parameterIndex); | |
} | |
const task = new Task(); | |
task.run('SomeTask'); | |
task.run(''); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment