Home > Back-end >  How to call a function on every function called
How to call a function on every function called

Time:09-07

As an example, I have 3 controllers and one function in node.js

function test() {console.log("controller called")}
controller1 = (req,res)=>{} 
controller2 = (req,res)=>{}
controller3 = (req,res)=>{}

So, how can I call the 'test' function when one of the controllers is called? Is there any possible way to do it without writing inside of it?

CodePudding user response:

Decorators are typically the way to go here, but in 2022 they are still in the proposal phase (although just recently reached stage 3) and aren't fully implemented into the language without the use of a transpiler.

In the meantime, you can still create a decorator, but you can't use the special @ syntax the proposal includes. So something like this will still work:

function logController(f) {
    return function(...args) {
        console.log("controller ran");
        return f(...args);
    }
}

controller1 = logController((req, res) => { })
controller2 = logController((req, res) => { })
controller3 = logController((req, res) => { })

If you happen to use babel, you can use their decorators plugin which implements the @ symbol.

CodePudding user response:

an idea to do this can be to redefine the controller methods to call test before call the original function

To avoid repeat same code for each function we can imagine loop on an array with function name

const functionWhereCallTest = ['controller1', 'controller2', 'controller3'];

functionWhereCallTest.forEach(func => {
  const originalFunc = window[func];
  window[func] = (req, res) => {
    test();
    return originalFunc(req, res);
  }
});

function test() {
  console.log("controller called")
}
controller1 = (req, res) => {
  console.log('controller1')
}
controller2 = (req, res) => {
  console.log('controller2')
}
controller3 = (req, res) => {}

const functionWhereCallTest = ['controller1', 'controller2', 'controller3'];

functionWhereCallTest.forEach(func => {
  const originalFunc = window[func];
  window[func] = (req, res) => {
    test();
    return originalFunc(req, res);
  }
});



controller1();
controller2();

  • Related