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