-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy path08-revocable-validated.js
62 lines (53 loc) · 1.93 KB
/
08-revocable-validated.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// 08 - Validation and revocable access
// library code --------------------------------------------------------------------------------
const options = {},
optionsRevocable = Proxy.revocable(options, {
set (obj, prop, value) {
if (prop === 'name') {
if (typeof value !== 'string' || value === '') {
throw new TypeError('"name" option should be a non-emtpy string');
}
} else if (prop === 'age') {
if (typeof value !== 'number' || value < 0 || value > 200) {
throw new TypeError('"age" option should be a number between 0 and 200');
}
} else {
throw new TypeError('The only valid options are "name" and "age"');
}
Reflect.set(obj, prop, value);
}
});
// sending the validated options proxy to the client
clientSetOptionsEventHandler(optionsRevocable.proxy);
// options arrived
console.log(options);
// revoking the client's access
optionsRevocable.revoke();
// simulating client actions afterwards
clientSometimeLater();
// client code --------------------------------------------------------------------------------
var globalOpts;
function clientSetOptionsEventHandler(opts) {
opts.name = 'Bob';
opts.age = 25;
try {
opts.age = 'old'; // TypeError: "age" option should be a number between 0 and 200
} catch (ex) {
console.error(ex);
}
try {
opts.height = 182; // TypeError: The only valid options are "name" and "age"
} catch (ex) {
console.error(ex);
}
// keeping the reference for stupid/harmful reasons
globalOpts = opts;
}
function clientSometimeLater() {
// trying to change it outside of the event handler
try {
globalOpts.name = 'Not Bob'; // TypeError: Cannot perform 'set' on a proxy that has been revoked
} catch (ex) {
console.error(ex);
}
}