0

I have two Express controllers in Node.js, A and B, and A has a function that returns data. I want B to call that function, intercept the answer and return it after refactoring. Something like this:

A{
  search(req,res){...}
}
B{
  wrapper(req,res){
    A.search(req,?).then((repsonse)=>{
      <refactor response>;
      res.send(refactoredData);
    })
  }
}

I can't figure out how to call A.search from B, and I don't want to change A, A.search has no next() in it, and if I call A.search(req,res) with the wrapper's parameters, I just redirected the call, right?

MrSimple
  • 599
  • 4
  • 14
  • I really don't see what the issue is here. You can call a method in a different class with the req/res params. Whilst the code above is clearly a non-runable example, I do wonder if you've thought about A.search resolving/rejecting the promise that B.wrapper is expecting. – Chris Adams Mar 12 '19 at 10:04
  • 2
    What's search and how it works? Is it your own function? Then rewrite it. The question lacks https://stackoverflow.com/help/mcve . There are no controllers in Node.js. If you're referring to Express, please, state this explicitly and add a relevant tag. This is actually the fundamental problem of Express that Koa solves. – Estus Flask Mar 12 '19 at 10:14
  • Possible duplicate of https://stackoverflow.com/questions/9896628/connect-or-express-middleware-to-modify-the-response-body – Estus Flask Mar 12 '19 at 10:21
  • @estus you're right, this is an Express problem, I just use the two hand in hand so I forgot to mention. It's my function, but it's not just a single function, it was an example. There are multiple functions that I want this to apply to. – MrSimple Mar 12 '19 at 10:24

1 Answers1

1
if you do not want to change the controller A. than you can create a callback function in B. and assign it to res.send like below :

A{
  search(req,res){ res.send(response);}
}

B{
   function sendcallback(response){
     <refactor response>;
  }
  wrapper(req,res){
    var fakeRes = {"send": sendcallback}
    A.search(req,fakeRes);
  }
}
Mohit Sahu
  • 177
  • 2
  • 17
  • (I updated the question to be Express.js specific) The idea was good, but it's not working with express Response. And I just realized that I'm piping the result into res, but at this point I can't put anymore research hours into this, I'll have to do it quick and dirty. Thank you for the idea! – MrSimple Mar 12 '19 at 11:51