Created
February 6, 2020 14:37
-
-
Save kanian/1d2e6a07f4d2c20471e2d7930bf16036 to your computer and use it in GitHub Desktop.
When parameter validation is enabled, validate the parameters
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
function schema(schema: Schema, validateParams: boolean = false) { | |
return function validateArgs(target: any) { | |
// save a reference to the original constructor | |
var original = target; | |
// wrap orginal constructor with validation behaviour | |
var f: any = function(...args) { | |
// When parameter validation is enabled... | |
if (validateParams) { | |
validateConstructorParams(target, args); // validate the parameters | |
} | |
const instance = new original(...args); | |
const { error } = schema.validate(instance); | |
if (error instanceof Error) { | |
throw error; | |
} | |
return instance; | |
}; | |
// set f's prototype to orginal's prototype so f keeps original's type | |
f.prototype = original.prototype; | |
return f; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment