JavaScriptFundamental (ES6), part 1
Validate object writes with a Proxy in JavaScript
109 a Proxy that validates every write
hardWrap an account object in a Proxy whose set trap checks each field against a rule, rejects an unknown field name outright, and refuses delete. Show that reads pass straight through, that the target is untouched by a rejected write, that writing to the target directly bypasses everything, and what a set trap returning false does under strict mode.
Stuck? Three hints, smallest first
- 1. The
settrap receives(target, key, value). Throwing from it is the clearest way to reject a write; returningfalseis the other way. - 2. Use
Reflect.set(target, key, value)to perform the write you approved, rather thantarget[key] = value. Same effect, and it returns the boolean the trap is supposed to return. - 3. A rule table keyed by field name gives you unknown-field detection for free: no rule, no write.
const guarded = (target, rules) =>
new Proxy(target, {
set(obj, key, value) {
const rule = rules[key];
if (!rule) throw new TypeError(`unknown field: ${String(key)}`);
if (!rule.check(value)) throw new TypeError(`${String(key)}: ${rule.why}`);
return Reflect.set(obj, key, value);
},
deleteProperty(obj, key) {
throw new TypeError(`${String(key)} cannot be removed`);
},
});
const rules = {
name: { check: (v) => typeof v === 'string' && v.length > 0, why: 'must be a non-empty string' },
balanceKobo: { check: (v) => Number.isInteger(v) && v >= 0, why: 'must be a whole, non-negative number of kobo' },
lga: { check: (v) => ['Yaba', 'Ikeja', 'Eti-Osa'].includes(v), why: 'must be a serviced LGA' },
};
const raw = { name: 'Ngozi Traders', balanceKobo: 450000, lga: 'Yaba' };
const account = guarded(raw, rules);
account.balanceKobo = 500000;
const accepted = [account.balanceKobo, raw.balanceKobo];
let rangeMessage = 'no error';
try { account.balanceKobo = -1; } catch (e) { rangeMessage = e.message; }
const afterReject = raw.balanceKobo;
let unknownMessage = 'no error';
try { account.blance = 1; } catch (e) { unknownMessage = e.message; }
const keyCountAfterTypo = Object.keys(raw).length;
let deleteMessage = 'no error';
try { delete account.lga; } catch (e) { deleteMessage = e.message; }
const readThrough = [account.name, account.lga, Object.keys(account)];
raw.balanceKobo = -999; // straight past the door
const bypassed = [account.balanceKobo, raw.balanceKobo];
const readOnly = new Proxy({ tier: 1 }, { set: () => false });
let refusal = 'no error';
try { readOnly.tier = 2; } catch (e) { refusal = e.constructor.name; }
console.log('accepted :', accepted);
console.log('rejected :', rangeMessage, '| target still:', afterReject);
console.log('unknown :', unknownMessage, '| delete:', deleteMessage);
console.log('bypass :', bypassed, '| false trap:', refusal);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a write that satisfies its rule lands on the target', accepted, [500000, 500000]);
test('a write that breaks it throws, carrying the rule its own words', rangeMessage, 'balanceKobo: must be a whole, non-negative number of kobo');
test('and the target is exactly as it was, so nothing half-happened', afterReject, 500000);
test('a misspelled field is an error rather than a brand new property', [unknownMessage, keyCountAfterTypo], ['unknown field: blance', 3]);
test('delete is refused too, by a trap of its own', deleteMessage, 'lga cannot be removed');
test('reads pass straight through, because there is no get trap to change them', readThrough, ['Ngozi Traders', 'Yaba', ['name', 'balanceKobo', 'lga']]);
test('writing to the target directly bypasses every rule, so keep the target private', bypassed, [-999, -999]);
test('under strict mode a set trap returning false throws instead of failing quietly', refusal, 'TypeError');
A Proxy is a door, not a lock. Every guarantee here holds only for code that goes through the proxy: the last-but-one assertion writes -999 straight onto the target and the rules never run. So the target must be unreachable — created inside the factory, closed over, never returned — or the validation is decoration.
Rejecting an unknown field is the part that earns the proxy its cost. A plain object accepts account.blance = 1 silently and the bug surfaces later somewhere unrelated; here it throws at the line that caused it. The rule table doubles as the schema, so there is one place to read to know what a valid account looks like.
Two mechanics worth knowing. Reflect.set is the function form of assignment and returns the boolean the trap is required to return, which is why the trap body ends with it rather than with a bare assignment plus return true. And a set trap has two ways to say no: throw, or return false. Returning false fails silently in sloppy mode and throws a bare TypeError in strict mode, which every module and every one of these panels is — so it throws, but with a message that says nothing about your rule. Throwing yourself is almost always clearer.