I'm working on a plugin system for mine service, and I load the plugins code from text using the new Function() construction. And I need somehow get access to the classes constructors link outside the plugin code. (for testing, unit tests)
Here is, I see a few solutions (if you know another solution, I'm open to your idea).
- add link to classes in the window object (global env)
- return the classes list as a result of loading and provide to the place where I need to use it.
The second one it too complicated for testing and required change the entire app for testing, that is not perfect. The first one creates one more global variable that is not perfect as well, but it's ok for testing environment (so for now I've chosen this solution).
The next question, how to do it reusable for any plugin (the class provider for testing env) should not depend on the specific plugin classes, but the plugin can depend on some function, and we can specify the correct plugin code structure.
I suppose that I could be done by using something like this (much simplified version):
function getClassInstanceFactoryMethod(){
class A{
}
class B{
}
return (className, params)=>{
return new className(...params); //need somehow choose the correct class and avoid the switch construction or manual collection in an array.
}
}
const buildObject = getClassInstanceFactoryMethod();
let objeA = buildObject('A'); //expected object of the A class
let objeA = buildObject('B'); //expected object of the B class
But the problem is avoided, enumeration of plugins class list (load it automatically).
Please any idea how to do it.
Aucun commentaire:
Enregistrer un commentaire