I use the following code that is working as expected and I want to get some feedback from the community how I can Improve it...
The code does the following:
Get Some request with specific action to run which is describe in JSON file e.g. URL is like aaa/bbb/invokeFn
Find this invokeFn in the config.json and call to function with the same name in the module
the files are located in folder under the project.
Please refer to my JavaScript and I need help with the followings
Does it make sense to divide it for two functions or maybe more?
How you put the variables better? Between those two function.
Any other feedback how can I improve the code in JS will be very helpfull
run: function (req, res, urlPath) {
var pluginPath = constants.INT;
var extPluginPath = constants.EXT;
var isFnCalled = false;
globby([objPath,extobjPath ])
.then(function (extensions) {
extensions.forEach(function (file) {
if (!isFnCalled) {
var filePath = file.split('/');
var fileName = filePath[filePath.length - 1];
var reqFile = "../" + filePath[2] + "/" + fileName;
isFnCalled = runFunction( req,res,reqFile,isFnCalled, urlPath);
}
});
}).catch(function (err) {
console.log('error: ', err);
}
)
}
};
var runFunction = function (req, res,reqFile, isFnCalled, urlPath) {
var rAction = urlPath[2];
//require JSON
var config = require(reqFile + 'on');
//require Module
var obj = require(reqFile);
for (var provider in config.providers[0]) {
if ((config.providers[0][provider].path === rAction && !isFnCalled)
&& (req.method === config.providers[0][provider].method.toUpperCase())) {
var fnName = config.providers[0][provider].function;
if (typeof obj[config.providers[0][provider].function] === "function") {
try {
isFnCalled = true;
//invoke function
console.log("Function " + fnName + " is called");
obj[fnName](req, res, urlPath);
}
catch (err) {
res.status(500).send("Error returned from obj " + err);
}
if (!res.headerSent) {
res.end("function " + fnName + " finish successfully ", 200);
}
}
}
}
return isFnCalled;
};
isFnCalled
in main function? \$\endgroup\$