I am getting this fun error when using the Proxy class:
TypeError: 'set' on proxy: trap returned truish for property 'users' which exists in the proxy target as a non-configurable and non-writable data property with a different value
I have a library which creates proxy object properties recursively, where any non-primitive property is a Proxy object itself, etc etc.:
let mcProxy = function (target) {
const mirrorCache = {};
return new Proxy(target, {
set: function (target, property, value, receiver) {
if (mirrorCache[property]) {
throw new Error(`property ${property} has already been set`);
}
mirrorCache[property] = true;
Object.defineProperty(target, property, {
writable: false,
value: (value && typeof value === 'object') ? mcProxy(value) : value
});
return true;
}
});
};
exports.create = function (val) {
val && assert.equal(typeof val, 'object', 'val must be an object');
return mcProxy(val || {});
};
actual usage of the above library code:
//bash
$ npm install proxy-mcproxy
// nodejs
let McProxy = require('proxy-mcproxy');
let val = McProxy.create();
val.users = [];
val.users = 3; // kaaaboom..error!
but when I set the users property the first time, I get the error in title of this question!
In my library code above, mirrorCache is a way to check if the property has been previously set. Want I want to do, is to throw an error, even if we aren't in strict mode, so mirrorCache appears to be necessary so that I do my own bookkeeping.
Perhaps there is a different or better way to achieve what I want to achieve? Here are my goals:
- Throw an error even if not in strict mode.
- Throw an error anytime the developer re-assigns a property. Each assigned property should be immutable.