0

In my nodejs application, I have one particular method that I want to call after execution of every method. And I don't want any code modification in methods that is being called.

I have implemented few logic to solve this problem, one of them is event based implementation,

  emitter.on("after", function(data){
    console.log("----after------", data);
    let req = {
        eventType: "user-event",
        appName: "Demo-app",
        payload: "function result: "+JSON.stringify(data),
    }
    producer.publishEvent(req);
   });

   userDetails = () => {
     let data = {"name": "xyz"};
     emitter.emit("after",data);
     return data;
   }

Also I got to know after searching that I can use AOP in javascript for this purpose. But it is not fully supported in ES6 and also as of now decorators will work with plugin only in ES6.(please correct me if I am wrong here)

So is there any other way I can do this implementation without modifying my methods?

Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
  • Have you tried async/await ? – virender nehra Oct 18 '19 at 07:51
  • @virendernehra To implement async/await I need to make changes on the method itself, that I want to avoid. I don't want to modify the methods that I want to track. – Sourabh Mishra Oct 18 '19 at 08:49
  • 1/2 ... Without transpiling processes / preprocessors, in a highly dynamic and interpreted language like JS, *method modification* always will be the base technique in order to fulfill/implement the mentioned requirements. – Peter Seliger Nov 05 '21 at 19:25
  • 2/2 ... And regarding the former `AOP` tag, wrapping and reassigning already declared functionality (be it functions or methods) misses any aspect of _AOP_. Any language which wants to qualify for the latter has to provide abstraction levels for at least `Joinpoint`, `Advice` and `Aspect`. The use case described by the OP should be referred to as method modification, and JavaScript of cause is well suited for this scenario and could easily provide a complete `context` aware toolset of method modifiers like `around`, `before`, `after`, `afterThrowing` and `afterFinally` via `Function.prototype` – Peter Seliger Sep 14 '22 at 14:29

0 Answers0