Friday 24 April 2020

Is it okay to share a function between two functions that are being called by API endpoints in NodeJS?

I tried searching about this but could not find a concrete answer. Is it safe to share functions within a NodeJS application?Lets say I have two API endpoints in a Node/Express app -// API endpoint 1. app.get('/endpoint1', function(req, res) { funcA(req.param, function(resultObj) { res.status(resultObj[0]).send(resultObj[1]); }); }); // API endpoint 2. app.get('/endpoint2', function(req, res) { funcB(req.param, function(resultObj) { res.status(resultObj[0]).send(resultObj[1]); }); }); The above endpoints are calling their respective functions (funcA and funcB) and each function call is being passed a callback which is responsible for responding to the client.Now if I have a third function (funcC), which has functionality common for funcA and funcB, can I have the two functions use funcC without any conflicts? Example -// Function A function funcA(param, callback) { // do something funcC(someParam, callback); } // Function B function funcB(param, callback) { // do something funcC(someParam, callback); } // Function C function funcC(param, callback) { // do something callback([200, 'Operation was successful!']); } Is the above logic safe assuming that any global variables being used are static? Would there be any issues if the "do something" part was making REST calls to another server?My reasoning that the above implementation would not be problematic is because I'm passing along the callback with the response object when making these function calls, so I'm assuming that the request and the response are "tied" this way. Is this correct?If multiple API endpoints are being served by a NodeJS application, does Node do anything to avoid race conditions like in a DB or is the developer responsible for avoiding such scenarios?Any other information regarding this would be really helpful.

Submitted April 24, 2020 at 09:01PM by mowgli1703

No comments:

Post a Comment