I have an object that I want to intercept access to any of its properties, and if it does not exists to return a fallback value. I tried the following implementation, but for some reason, I get back a Proxy object instead of the fallback value.
const isObject = obj => typeof obj === 'object';
const hasKey = (obj, key) => key in obj;
const isNullOrUndefined = obj => obj === null || obj === undefined;
const obj = {
keyOne: ''
};
const returnPropertyOnObject = (target, property) => {
if (isObject(target[property])) {
return safe(target[property])
}
return target[property];
}
function safe(obj) {
return new Proxy(obj, {
get: (target, property) => {
if (hasKey(target, property) && !isNullOrUndefined(target[property])) {
returnPropertyOnObject(target, property)
}
return new Proxy({}, {
get: function(target, property) {
return 'MISSING!!';
}
});;
}
});
}
const wrap = safe(obj);
console.log(wrap.notExists);
console.log(wrap.notExists.deep.nested.nested);
Moreover, I sometimes get properties like toJSON, or toString inside the Proxy.
What am I missing?