Javascript Proxy: prevent any further properties to get called when a property does not exist on a multi level object

Viewed 513

Context

while working on a modular architecture, I try to make as much "weak" dependencies as possible. For that purpose I use a "bridgeService" that handle all inter-module interactions.

Problem

I would use the bridgeService as follow:

// in moduleA.js
bridgeService.moduleB.functionA();

But if moduleB does not exists this wil throw an error cannot read property functionA of undefined or bridgeService.moduleB.functionA is not a function.

Expectations

My will is that it fails softly. If any of the properties in the property chain is missing, this will log a warning, return null or false AND prevent all further properties to get called.

Actual code

Here is what I got at the moment:

// Proxy handler
const safeNotInstanciatedWarningProxy = {
    get: function (object, prop) {
        if (prop in object) return object[prop];
        else {
            console.warn(`${prop} not defined`);
            return new Proxy({}, safeNotInstanciatedWarningProxy);
        }
    }
}

const bridgeService = new Proxy({}, safeNotInstanciatedWarningProxy)

This will never throw the first cannot read property functionA of undefined error. But when the last function get called, I can't get rid of the is not a function error.

Is there a way to achieve exactly what I want in javascript ? If not, what would be the best alternative ?

Thanks for your lights

1 Answers

I can't get rid of the is not a function error.

You can make the proxy wrap a function instead:

return new Proxy(() => {
    console.warn("… and is not a function");
}, safeNotInstanciatedWarningProxy);

Of course, this will fail once your modules expects the methods to return something.

Here is an example on codePen

Related