Created
February 6, 2020 15:22
-
-
Save kanian/6329591968093543e69ba7ee004a2d43 to your computer and use it in GitHub Desktop.
Property Schema Decorator
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 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