I want to include the factory pattern in my modules. I have a module ServiceFactory.js that looks like this:
exports.createService = function(serviceName, paramObj){
return require('Services/'+serviceName).Service.new(paramObj);
};
This module should require other modules (Services) by their names and create an instance. The general Service.js lookes like this:
const Base = require('base').Base;
exports.Service = Base.extend({
getName: function(){
return this.name;
},
invoke: function(){
//do something
},
});
All other Services extend the base Service. I collect all Services in a subfolder “Services” in “lib”. When I now use the createService method of my factory I get an error like: “Module: ServiceFactory … has no authority to load Service/…”
Is there a way to grant ServiceFactory the authority to load my Services or is there another way to achieve my goal?
The Add-on SDK resolves all requirements when the add-on is packaged, it doesn’t happen at run-time. I guess that this is done mostly for performance reasons (modules can be loaded from several locations, searching these location when the extension is running can be slow) but there is a security aspect as well – even if a module is compromised (unintentionally runs code that it got from a web page), it still cannot load any additional modules, in particular not the
chromemodule. But the end result is: you cannot decide dynamically which modules you want to use, you can only load the modules that you explicitly require in your source code.The work-around in your case would be adding a function that is never called but has all the necessary
require()calls to make sure that the SDK resolves them:Having this function in
ServiceFactor.jswill make sure that thecreateService()function can require these modules.