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?

4
  • 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. Commented Mar 12, 2019 at 10:04
  • 2
    What's search and how it works? Is it your own function? Then rewrite it. The question lacks 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. Commented Mar 12, 2019 at 10:14
  • Possible duplicate of stackoverflow.com/questions/9896628/… Commented Mar 12, 2019 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. Commented Mar 12, 2019 at 10:24

1 Answer 1

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);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

(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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.