Skip to content

Instantly share code, notes, and snippets.

@kanian
Created February 6, 2020 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanian/1d2e6a07f4d2c20471e2d7930bf16036 to your computer and use it in GitHub Desktop.
Save kanian/1d2e6a07f4d2c20471e2d7930bf16036 to your computer and use it in GitHub Desktop.
When parameter validation is enabled, validate the parameters
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