-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2-members-validation.js
48 lines (46 loc) · 1.47 KB
/
2-members-validation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Function to validate object properties before
* assigning them to a specific value.
*
* @param {Object} target Target object containing the properties to validate.
* @param {Object} validator Validator object containing the validation functions
* for target object properties.
*
* @return {Proxy} Proxy object.
*/
const
validate = (target, validators) => {
const
handler = {
/**
* Property value setter trap.
*
* @param {Object} target Target object containing the properties to validate.
* @param {String} prop Property name.
* @param {*} val Property value.
*
* @return {void}
*
* @notes
* [1] : Checks if the property already exits on the target object,
* if not throw an error.
*
* [2] : Checks if the validator function is passed, if not throw an error.
*/
set(target, prop, val) {
// [1]
if (target.hasOwnProperty(prop)) {
const
validator = validators[prop]; // [1]
// [2]
if (!!validator(val))
return Reflect.set(target, prop, val);
else
throw new Error(`ValidationError: Can't assign "${val}" to "${prop}"`)
} else {
throw new Error(`"${prop}" isn't a valid property`)
}
}
};
return new Proxy(target, handler)
};