Last active
October 4, 2018 02:02
-
-
Save dhl/380460093b3b4a13fce09975a7870b94 to your computer and use it in GitHub Desktop.
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
const validationFunctionMetadataKey = Symbol.for('validate::func') | |
function makeParamValidator(validator: Function) { | |
return ( | |
target: Object, | |
propertyKey: string | symbol, | |
parameterIndex: number | |
) => { | |
let existingValidationParameters: Map<any, Function> = | |
Reflect.getOwnMetadata( | |
validationFunctionMetadataKey, | |
target, | |
propertyKey | |
) || new Map() | |
existingValidationParameters.set(parameterIndex, validator) | |
Reflect.defineMetadata( | |
validationFunctionMetadataKey, | |
existingValidationParameters, | |
target, | |
propertyKey | |
) | |
} | |
} | |
export function validate( | |
target: any, | |
propertyName: string, | |
descriptor: TypedPropertyDescriptor<(...args: any[]) => any> | |
) { | |
let method = descriptor.value as Function | |
descriptor.value = function() { | |
let validateFuncs: Map<any, Function> = Reflect.getOwnMetadata( | |
validationFunctionMetadataKey, | |
target, | |
propertyName | |
) | |
if (validateFuncs) { | |
for (const [parameterIndex, validator] of validateFuncs) { | |
validator(arguments[parameterIndex], { | |
parameterIndex, | |
propertyName, | |
target | |
}) | |
} | |
} | |
return method.apply(this, arguments) | |
} | |
} | |
function isDigest(str: string) { | |
return /^0[xX][0-9a-fA-F]{64}$/.test(str) | |
} | |
function reportError( | |
typeName: string, | |
param: string, | |
invocationMetadata: any | |
): void { | |
const { parameterIndex, propertyName, target } = invocationMetadata | |
const paramPos = parameterIndex + 1 | |
throw Error( | |
`Expected ${typeName} for parameter "${paramPos}" for ` + | |
`method "${propertyName} "in class "${target.constructor.name}". ` + | |
`Received: ${param}` | |
) | |
} | |
export function requireDigest() { | |
const validator = (param: string, invocationMetadata: any) => { | |
if (!isDigest(param)) { | |
reportError('Digest', param, invocationMetadata) | |
} | |
} | |
return makeParamValidator(validator) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment