loading javascript classes stored in database

Tags: ,



I have a react application, using webpack. In my application, I allow users to overwrite default behaviors with their own custom behavior.

For example lets say the application has a button that when clicked would alert a message to the user and this user would rather not be annoyed with an alert box they would rather it be a console.log statement. In the admin console, they would upload a class, that class must have an method named exec(). Then they would click on the button (in an admin console) and change its onClick functionality to be the name of their custom class.

Currently, when they upload a file, after checking to make sure it is valid js class with a exec method, the class is stored in a database as text.

What I want, is that when the application starts is that the applications reads all the classes and store them as a map with their names as the key. I can retrieve the classes from the database (as text) how can I turn that into an object?

edit added code here is an example class

class CustomClass {

  exec(params) {
  console.log('you are in a custom class');
 }
}

getting the custom classes

 const apiUrl = 'https://api.example.com/customClasses';
    fetch(apiUrl)
      .then((response) => response.json())
      .then((data) => console.log(data));

this would give a json that looks like

{
    "CustomClass":  "class CustomClass {rnrn  exec(params) {rn  console.log("you are in a custom class");rn }rn}",
    "CustomClass2":  "class CustomClass2 {rnrn  exec(params) {rn  console.log("you are in a custom class2");rn }rn}"    
}

Answer

So, it turns out you can just use eval with parenthesis as seen here

let userClasses = {
    "CustomClass":  "class CustomClass {rnrn  exec(params) {rn  console.log("you are in a custom class");rn }rn}",
    "CustomClass2":  "class CustomClass2 {rnrn  exec(params) {rn  console.log("you are in a custom class2");rn }rn}"    
}

for (const userClassName in userClasses) {
    const userClass = eval(`(${userClasses[userClassName]})`);
    let userClassObject = new userClass();
    userClassObject.exec();
}

Would this solve your problem?



Source: stackoverflow