Skip to content

Instantly share code, notes, and snippets.

@kanian
Created February 6, 2020 15:22
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/6329591968093543e69ba7ee004a2d43 to your computer and use it in GitHub Desktop.
Save kanian/6329591968093543e69ba7ee004a2d43 to your computer and use it in GitHub Desktop.
Property Schema Decorator
function propertySchema(schema: Schema) {
return function(target: Object, key: string | symbol): void {
// The property
let val = target[key];
let propertyName = String(key);
// Generate getter and setter
const getter = () => {
return val;
};
const setter = value => {
// Validate
const { error } = schema.validate(value);
// Throw an error if validation fails
if (error instanceof Error) {
// A descriptive error message
error.message = error.message.replace('"value"', `"${propertyName}"`);
throw error;
}
// Else, set value
val = value;
};
// Append getter and setter to the target
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment