user1735921
user1735921

Reputation: 1389

Making beforeFilter for module functions?

A beforeFilter is that block of code which is executed before calling any function. I am new to javascript.

Lets say I have a module:

SomeModule.js

module.exports = {

    someFunction: function (arg) {
        //some logic here
    },
}

Now whenever I want to call the above function, I will do:

SomeModule.someFunction("helloWorld");

Like this you can assume I got many functions in the module but I want to execute some code before calling any function of the module, lets say I want to execute this line:

console.log("BeforeFilter Called");

So question is: How can I ensure that the line gets executed before calling any function of the module ?

Upvotes: 1

Views: 48

Answers (1)

Michał Perłakowski
Michał Perłakowski

Reputation: 92609

You have to iterate over properties of SomeModule and overwrite all properties which are functions:

const SomeModule = {
  someFunction(a, b) {
    console.log('some function', a + b);
  }
};

for (const i in SomeModule) {
  if (typeof SomeModule[i] === 'function') {
    const originalFunction = SomeModule[i];
    SomeModule[i] = function (...args) {
      console.log('BeforeFilter Called');
      originalFunction(...args);
    };
  }
}

SomeModule.someFunction(3, 4);

Upvotes: 2

Related Questions