Is there a better way than eval () in this scenario?

It is a web application using Google Apps Script that acts as a user accessing the application.

We have user data and code for some users.

This user information is in a text file in the developer's Google Drive, but only for viewing access from a specific user.

The content of this text file may look like dummy code:

var oConfig = {
  some : "OK",  
  getinfo : function (s) {
    return this.some + s;
  }
}

      

To get this user data / code in the application, we can use eval () as shown below:

  var rawjs = DriveApp.getFileById(jsid).getBlob().getDataAsString();
  eval(rawjs);
  Logger.log(oConfig.getinfo("?")); // OK?

      

My questions:

  • Is there a better way to achieve this goal than eval ()?

  • Is eval () safe enough in this case, given that the text file is only being edited by the developer?

Thanks, Fausto

+3


source to share


2 answers


Okay, it looks safe enough. But using eval has other problems, like making it difficult to debug the code and possibly some other problems.

If you create such custom data in your code, I will assume that the variety of such settings is enumerable. If so, I would leave the code in your script and only save the data to Disk and use indicators (like function variant names) how to rebuild the config object in the script. For example:



function buildConfig(data) {
  var config = JSON.parse(data); //only data, no code
  config.getInfo = this[config.getInfo]; //hook code safely
  return config;
}

function customInfo1(s) { return this.some + s; }

function customInfo2(s) { return s + this.some; }

function testSetup() {
  //var userData = DriveApp.getFileById(jsid).getBlob().getDataAsString();
  var userData = '{"some":"OK", "getInfo":"customInfo1"}'; //just for easier testing

  var config = buildConfig(userdata); //no eval

  //let test it
  Logger.log(config.getInfo('test'));
}

      

+4


source


  • It seems safe. But it will make the execution process slower if you have large data in a text file.

  • I would still suggest using JSON.parse () instead of eval () to parse your user data / code.

    {
      some : "OK",         
      getinfo : "function(s){return this.some +\" \"+ s;}"       
    }        
    
    var rawjs = DriveApp.getFileById(jsid).getBlob().getDataAsString();        
    var oConfig = JSON.parse(rawjs, function(k,v){//put your code here to parse function}); // avoid eval()        
    Logger.log(oConfig.getinfo("?"));
    
          



+1


source







All Articles